String 、StringBuilder 、StringBuffer

Is it variable

The string in the String object is immutable, and a char array is defined in its class to store the string

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

StringBuilder、StringBuffer类图

It can be seen from its class diagram that both classes inherit from the AbstractStringBuilder class

abstract class AbstractStringBuilder implements Appendable, CharSequence {
    /**
     * The value is used for character storage.
     */
    char[] value;

It can be seen that the string array in AbstractStringBuilder is a variable value, so StringBuilder and StringBuffer are variable strings

String memory analysis: https://zhuanlan.zhihu.com/p/107781993

Thread-safe

String values because it is so constant thread is the security of

StringBuilder thread is not safe

    @Override
    public StringBuilder append(CharSequence s) {
        super.append(s);
        return this;
    }

StringBuffer uses synchronized synchronization method to achieve thread safety :

    @Override
    public synchronized StringBuffer append(CharSequence s) {
        toStringCache = null;
        super.append(s);
        return this;
    }

Performance gap

每次改变String都需要新建一个String并且将引用指向该Sting,因此性能低下

相同情况下使用 StringBuilder 相比使用 StringBuffer 仅能获得 10%~15% 左右的性能提升,但却要冒多线程不安全的风险

Recommendations

- 少量数据:String
- 单线程大量数据:StringBuilder
- 多线程大量数据:StringBuffer

javac string splicing automatic conversion

源码:

```java
    public static void main(String[] args) {
        String a = "a";
        String b = "b";
        String c = a + b;
        String d = "a" + "b";
    }
```

利用jad工具反编译代码:

```java
    public static void main(String args[]){
        String a = "a";
        String b = "b";
        String c = (new StringBuilder()).append(a).append(b).toString();
        String d = "ab";
    }  
```

可以看到当两个字符串“a"和”b"直接执行拼接操作时,javac会自动将其合并,而使用String相加时会自动转换为StringBuilder的拼接

Guess you like

Origin www.cnblogs.com/YuanJieHe/p/12748913.html