Monday, March 20, 2006

StringBuffer Myth

I have noticed that a lot of people are wasting their precious time changing code that contains "+" overloaded String operator the following way :
For eg.
1 ) String sTemp = "a" + "b" + "c";is being replaced with
2 )StringBuffer sBuffer = new StringBuffer()
String sTemp = sBuffer.toString();

Now the point is for simple string concatenations such as the above the compiler itself does the conversion to StringBuffer. Thus the code in 1) gets converted to code in 2) during compilation time conversion to platform independant byte form...

So there is no need for us to do this explictly....But yes, there will be a remarkable advantage when we have String concatenation in a for loop...
for eg, if the above code was within a for loop.....for eg:
for(int i=0;i<n;i++)
{ sTemp = "a" + "b" + "c";}

Then it makes sense to use StringBuffer, otherwise a new String Buffer object will be created for each iteration of the loop. So in such cases we can instantiate the StringBuffer outside the loop and just use "append" inside the loop..