Does it help GC to null local variables in Java

前端 未结 15 2050
旧巷少年郎
旧巷少年郎 2020-12-02 13:06

I was \'forced\' to add myLocalVar = null; statement into finally clause just before leaving method. Reason is to help GC. I was told I will get SMS\'s during n

15条回答
  •  清歌不尽
    2020-12-02 13:55

    You are correct. Nulling out a variable that will immediately fall out of scope anyway is unnecessary and makes no difference whatsoever to GC. All it does is clutter the code. In Effective Java 2nd Edition, the author recommends against unnecessary nulling out of local variables. See Effective Java, 2nd Edition, Item 6: Eliminate obsolete object references, for a full writeup.

    You can also see this in the article Creating and Destroying Java Objects, at InformIT. Read the entire article to find the place where Joshua Bloch agrees with you.

    When a local variable falls out of scope, it is exactly the same as if you null the reference to it.

    EDIT: Add link to Effective Java 2nd Edition at Sun website

提交回复
热议问题