When we work on Concatenation of strings in java
why StringBuffer is faster than String In every definition it is said that Stringbuffer is faster thaan string but haven't got clear details on how it is made possible
When we work on Concatenation of strings in java
why StringBuffer is faster than String In every definition it is said that Stringbuffer is faster thaan string but haven't got clear details on how it is made possible
String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer is mutable so they can change their values. Thats why StringBuffer is faster than String.
Every time you concatenate String
objects, the content of the strings is copied into a new String
instance. So if you have a string 50 characters long, and you append another character, then those 50 characters all have to be copied into a new string.
StringBuffer
(or StringBuilder
) has a char
array whose length may be greater than the current amount of content it contains. As more text is added to the StringBuffer
, the array gets filled up until the capacity is reached. The content of the array does not need to be completely copied every time.
(In practice, Java is smart enough to optimise many string concatenations to use StringBuilder
instead, even if you don't write them explicitly.)
From java documentation ;
To improve performance, instead of using string
concatenation
, useStringBuffer.append()
String objects are immutable—they never change after creation. For example, consider the following code:
String str = "testing"; str = str + "abc";
The compiler translates this code as:
String str = "testing"; StringBuffer tmp = new StringBuffer(str); tmp.append("abc"); str = tmp.toString();
Therefore, copying is inherently expensive and overusing it can reduce performance significantly.