常用类关于引用类型的问题

String,StringBuffer,StringBuilder的区别与联系?

 

1) String is invariant. Once a Sring object is created, you can not change it. StringBuffer and StringBuilder can change. They are inented to overcome the problem of concatenating strings and reduce memory fraction.

2)StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.

StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.

3)StringBuffer is less efficient than StringBuilder.

StringBuilder is more efficient than StringBuffer.

 

介绍

String:不可变的字符序列

StringBuffer:可变的字符序列,效率低,线程安全

StringBuilder:可变的字符序列,效率高,线程不安全

区别

区别就在于看你使用的场景,如果只是少量的字符操作,用String即可

如果是在多线程情况下有拼接字符串的情况下,用StringBuffer,这个是保证线程安全的,虽然效率会低一些

如果是在非多线程的情况下有拼接字符串的情况下,用StringBuilder,他虽然线程不安全,但是效率会高一些

为什么拼接的时候不推荐使用String呢,因为String的值是不可变的,这就导致每次对String的操作都会生成新的String对象,不仅效率低下,而且浪费大量优先的内存空间