Why should you be careful about String Concatenation(+) operator in Loops?
Consider the code below:
String s3 = "Value1";
String s2 = "Value2";
for (int i = 0; i < 100000; ++i) {
s3 = s3 + s2;
}
How many objects are created in memory? More than 100000 Strings are created. This will have a huge performance impact.
How do you solve above problem?
StringBuffer str=new StringBuffer("Hello")
StringBuffer str1= str.append("World")
SOP(str)//Helloworld
SOP(str1)//Helloworld
The easiest way to solve above problem is using StringBuffer. On my machine StringBuffer version took 0.5 seconds. String version took 25 Seconds. Thats a 50 fold increase in performance.
StringBuffer s3 = new StringBuffer("Value1");
String s2 = "Value2";
for (int i = 0; i < 100000; ++i) {
s3.append(s2);
}
No Comments Yet!!