What makes SB improves its performance

Is heap storage the reason for it ???

Performance depends what kind of task you are doing. If most of the operations involve modifying a string again and again, then its better to use StringBuilder object.
So in these cases, the primary reason for low performance of String class is its immutable property.
say for example modifying a string a million times.
String str = “”;
for(int i=0;i<1000000;i++){
str = str + “abc”;
}
In each iteration of loop, a new string object will be created(since str is immutable and it cant be modified), the old content is copied to new object and new content(“abc”) is appended in this new string object.
so the time complexity actually is x+2x+3x+4x+…, here x is length of content being appended(here 3 for “abc”).
time complexity is x+2x(x for copying old content and x for new content) + 3x(2x old content and x new content)+4x+5x…so on. this is O(n^2).

whereas StringBuffer is mutable, so the complexity for the the same operation with stringbuilder will be linear. the question is, How is mutable property implemented?
StringBuffer is actually implemented using character array and the size of character array is changed as per requirement. when this size changes, at that time only copying occurs. and this size change conditions(you can read about this through web) are in such a way that the amortized cost is linear.

Thanks.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.