http://plainoldjavaobject.blogspot.in
Smarty Ravi wrote:Immutable objects should be used very restrictively. If you got the String variable which changes many times in a code, then i prefer to make use of String buffer instead of String variable.
Smarty Ravi wrote:Because if we go on changing the value of a string variable, then for each time the value changes, jvm creates a new memory with new value and maps the new memory with string variable, so the previous memory is unused. This unused space will get freed only when JVM Calls GarbageCollector. Until then this space would be useless.
Smarty Ravi wrote:In larger applications, where the values changes often then i prefer stringbuffer, because use of string in such scenarios would lead to memory problem.
I disagree. Immutable objects have many advantages - they make your code simpler and especially if your program is multi-threaded immutable objects are good, because they are thread-safe.
Java's garbage collector is very smart and efficient, especially with short-lived objects. The latest Java 6 versions also have advanced optimizations (escape analysis - I won't explain in detail because it's certainly not a beginners' topic) that make creating and garbage collection temporary objects almost free. Don't do these kind of optimizations manually because you think creating and destroying objects is expensive, because usually it is not.
There are certain circumstances in which using StringBuilder (note, you should be using StringBuilder instead of StringBuffer) is preferable above using String. For example, when you have to concatenate things in a loop, it's more efficient to use a StringBuilder. But do not use StringBuilder or -Buffer as a general replacement for String, because you think it is somehow more memory-efficient.
Consider Paul's rocket mass heater. |