Fastest way to release memory of stringbuilder

  • A+

What is the fastest way to release memory of stringbuilder .

 StringBUilder sb = new StringBuilder();  sb.apppend(maximum value possible); 

Below are the code snippets which i tried to release memory as fast as possible and make the object eligible for garbage collection

Way 1 -

sb = null; 

As per my understanding all the data in the stringbuilder will be deleted and object will be eligible for garbage collection as soon as it is kicked in, but the memory of the text which is occupied by stringbuilder will be released. Also will the string value in it also be deleted from heap or will be stored in string pool ?

Way 2 -


This will reset the lenght of string builder but it will not be garbage collected

Way 3 -


This will reset the string builder by deleting all the data in it but it will not be garbage collected

Way 4 -

 sb.delete(0,sb.length());  sb = null; 

This will reset the string builder and also make it eligible for garbage collection


Simple: go with

sb = null; 

and forget about the rest.

Why? As soon as the GC can decide that an object is eligible for garbage collection, it also knows that all the things referenced from that object are eligible. And given the fact that you have no control about the GC kicking in and cleaning up objects and releasing memory, the above assignment is really good enough.

As it communicates your intent clearly, and then helps the GC to do its job. Actually well written code would probably not even need that statement.

Now, maybe that is actually not good enough. But then we would be talking about a real performance issue, in a very defined and narrow context. In that case, you don't rely on hearsay, you start measuring.

In other words: if you don't have a real performance issue that manifests in your setup, and that requires action, then you go with simple, clear code, avoiding all kinds of "source code level" optimisations. But if you have a real performance issue, than you treat that accordingly: by identifying the root cause, and probably by measuring how different options work out in reality.

Anything else smells of premature optimisation!


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: