In Java, do you know about the pitfall of using string concatenation within loops??
Since strings are immutable in JAVA, when we try to append another char to a string, it creates a new copy of the string and updates the copy instead of the original string.
Example :
String s = "value";
s.concat("d");
Enter fullscreen mode Exit fullscreen mode
On doing so, value of string s is not changed rather a new updated copy of string s is created in heap.
Now think, if concatenating string creates one another copy of string object, what would happen if do string concatenation within a loop.
string s = "coding";
for(int i = 0;i < 100000;i++){
s += "java";
}
Enter fullscreen mode Exit fullscreen mode
This would create 100000 new copies of string object s!!!
Creating 100000 copies leads to significantly impacting code performance. So you must be thinking what’s the solution??
We have two alternative to tackle this issue?
StringBuffer & StringBuilder
Both serve the purpose of avoiding creation of string objects upon concatenation!
Example:
StringBuffer s3 = new StringBuffer("value");
String s2 = "value2";
for(int i = 0;i < 100000;i++){
s3.append(s2); // s3 = s3 + s2;
}
Enter fullscreen mode Exit fullscreen mode
In this scenario, no creation of string objects happen! Cool, isn’t it?
Same can be achieved with StringBuilder, so what’s the difference between the two then??
StringBuilder is not thread safe while StringBuffer is!
But more on threads later!! Hope you enjoyed this !!
暂无评论内容