Abstract: This article will introduce the different among String, StringBuilder and StringBuffer. It will help to decide which one will be used during development.
String
The string is immutable and once a String is created, it cannot be modified. So when we change String, we always create a new reference to String.
Where store in memory
- create in “String constant pool”, which is inside the Heap memory and it can be reusable.
1 | String str1 = "value"; |
- create on the heap
1 | String strHeap = new String("value") |
Attention!
DONT DO Concatenation operation for String in the loop, because too many String will be stored.
StringBuffer
Use StringBuffer for concrete String in a loop.
VS String
- both are thread safe
- StringBuffer is implemented by using synchronized keyword on all methods.
- The string is immutable, StringBuffer is used to represent the values that can be modified.
- StringBuffer has high performance for the situation where String value need be modified too many times.
StringBuilder
VS StringBuffer
StringBuffer: thread safe
StringBuilder: not thread safe
why it is suggested by IDE or Sonar
Because if there isn’t the scenario that multiple threads operating on the same object, the StringBuilder has better performance, because the thread safe need synchronized keyword which reduces the performance.
This article discusses the thread safe or not.
https://blog.csdn.net/xiao__gui/article/details/8934832