Storage time difference.

So let’s see how each one is stored, right

String



StringBuilder



Abstractbuffer is derived from AbstractStringBuilder. StringBuffer does not define its own container, but inherits its parent’s container

This is where StringBuilder stores characters

As you can see above,String characters are stored ina final char array (similar to pointer constants in C), while StringBuilder characters are stored ina normal CHAR array

<hr>

The difference in operation

A String of operations



You can view the addition of these two operations like this

final char c1[] = {'the first'.'一'.'个'.'word'.'operator'.'string'};
​final char c2[] = {'the first'.'二'.'个'.'word'.'operator'.'string'};
​final char c3[] = new char[12];
c3[] =  {'the first'.'一'.'个'.'word'.'operator'.'string'.'the first'.'二'.'个'.'word'.'operator'.'string'}; c1 = c3; // This paragraph is only for understandingCopy the code

All String operations create an appropriately sized char array [], so the next time a String is concatenated it will be redistributed.

The StringBuilder operations





The StringBuilder characteristics

  • StringBuilder initialization capacity is 16(no parameter construction)

  • Char [] = newCapacity = (value.length << 1) + 2; So this is length times 2 plus 2

  • The StringBuilder calculates whether it has enough capacity each time and reassigns a char[] that is twice its capacity +2 if the required capacity is no less than its own capacity. So it saves a lot of creating char[].

Plain conclusion

  • String is slow because most of the CPU resources are wasted on allocating and copying resources, and it consumes more memory than StringBuilder.

  • StringBuilder is faster because it allocates less memory than String, so it has fewer copies and memory footprint.

  • Due to the GC mechanism, even if the original char[] is not referenced, it is not collected until the GC is triggered. Too many String operations generate a lot of garbage and consume memory.

advice

  • If the target string requires a lot of concatenation, then StringBuilder should be used.

  • On the other hand, if the target String has few operations or is a constant, use String directly.