-3

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

Sivaprakash B
  • 163
  • 1
  • 15
  • No they are just mentioning stringbuffer is faster thaan string but i am asking how it is made possible? – Sivaprakash B Oct 12 '18 at 11:04
  • 1
    You are probably reading an old textbook or blogpost. The difference in speed in recent versions of Java is about the same for simple concatenation, and even where it matters you should probably use `StringBuilder` instead of `StringBuffer`. – Mark Rotteveel Oct 12 '18 at 15:22

3 Answers3

4

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.

Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
3

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.)

khelwood
  • 55,782
  • 14
  • 81
  • 108
1

From java documentation ;

To improve performance, instead of using string concatenation, use StringBuffer.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.

drowny
  • 2,067
  • 11
  • 19