Speed issue while appending strings
java, performance, string
Solution
`s+=String.valueOf(j);` needs to allocate a new `String` object every time it is called, and this is expensive. The `StringBuffer` only needs to grow some internal representation when the contained string is too large, which happens much less often.
It would probably be even faster if you used a `StringBuilder`, which is a non-synchronized version of a StringBuffer.
One thing to note is that while this does apply to loops and many other cases, it does not necessarily apply to all cases where Strings are concatenated using `+`:
String helloWorld = getGreeting() + ", " + getUsername() + "!";
Here, the compiler will probably optimize the code in a way that it sees fit, which may or may not be creating a `StringBuilder`, since that is also an expensive operation.
Problem
Whenever I try to add the numbers in string like: ``` String s=new String(); for(int j=0;j<=1000000;j++) s+=String.valueOf(j); ``` My program is adding the numbers, but very slowly. But When I altered my program and made it like: ``` StringBuffer sb=new StringBuffer(); for(int j=0;j<=1000000;j++) sb.append(String.valueOf(j)); ``` I got the result very quickly. Why is that so?