Thinking java String concatenation internally uses StringBuffer to do the concatenation operation, we do concatenation as mentioned below in java code,
String str=a+b; a and b is string objects.
java compiler compiles above code in this fashion:
String str=(new StringBuffer()).append(a).append(b).toString());
Above code creates two objects, and as you must be knowing that java maintains the string data in char array which is also an object so it creates 1 more object. So in total 3 objects gets created for one concatenation operation. Please note that object creation is one of the costliest operation in java.
I created one test program just to see the performance difference and results were dramatic... i ran both loop in same program 1 million times. See the time difference... So based on below result its recommended to use StringBuffer.append whenever you are doing any concatenation operation in java...
time taken by string: 78080 (ms)
time taken by String buffer: 31 (ms)
time taken by String buffer: 31 (ms)
No comments:
Post a Comment