• Post Reply Bookmark Topic Watch Topic
  • New Topic

setting String to null  RSS feed

 
satish pune
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If in a Java method at the end - I explicitly set the String variable to null
will this cause any performance improvement ?
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, the virtual memory address space is so vast that the only programs that need to care about releasing memory are ones with very large structures full of objects or object references.

Second, if the reference to the String is a local variable, the reference will go away as soon as the method completes, which has the same effect on garbage collection as setting the variable to null.

Third, many usages put the string in the string literal pool, which is not garbage collected. The exceptions are like
String s1 = new String("abc"); and
String s2 = s3 + s4;

If you have millions of unique references to this sort of String object, you need to consider memory management techniques like s2=null and the classes in java.lang.ref.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to optimize your code, setting variables and methods to final whenever appropriate will make a difference, though most programs run so fast you probably won't see the difference.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the Performance forum...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!