String、StringBuffer和StringBuilder的区别
可变性
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ private final char value[]; ...................
public final class StringBuffer extends AbstractStringBuilder abstract class AbstractStringBuilder implements Appendable, CharSequence { /** * The value is used for character storage. */ char[] value;
线程安全性
@Override public synchronized int length() { return count; } @Override public synchronized int capacity() { return value.length; } @Override public synchronized void ensureCapacity(int minimumCapacity) { super.ensureCapacity(minimumCapacity); }
性能
每次修改String的值都会重新生成一个新的String对象,然后再将指针指向新的String对象,StringBuffer和StringBuilder每次都是对象本身进行操作,而不是生成新的对象。StringBuilder的性能会比StringBuffer好一点,不过却要冒多线程不安全的风险
总结