String、StringBuffer和StringBuild区别

String

String是不可变对象,即对象一旦生成,就不能被更改。对String对象的改变会引发新的String对象的生成。

1 String s = "abcd";
2 s = s+"efgh";

执行以下代码实际上是生成了一个新的String对象。然后让引用指向新的String对象。所以内容经常改变的字符串不要使用String类型,由于这样会造成内存中大量的无引用对象,然后JVM的GC就会开始工作。

例如如下代码将会产生10000个五引用对象。

 1 String S1 = “abc”; 
 2 
 3         For(int i = 0 ; i < 10000 ; i ++)   
 4 
 5         { 
 6 
 7                S1 + = “def”; 
 8 
 9                S1 = “abc”; 
10 
11 } 

StringBuffer

StrinhBuffer:每次都对对象本身进行操作,而不是生成新的对象。所以在字符串内容不断改变的情况,建议使用StringBuffer。

String对象的字符串拼接其实是被JVM解释成了StringBuffer对象的拼接,所以这些时候String对象的速度并不会比StringBuffer慢。

例如:如下代码,String的效率远比StringBuffer快。

1  String S1 = “This is only a” + “ simple” + “ test”; 
2  StringBuffer Sb = new StringBuilder(“This is only a”).append(“simple”).append(“ test”); 

这是因为,在JVM眼里:String S1 = “This is only a” + “ simple” + “ test”;就是String S1 = “This is only a simple test”;

StringBuild

StringBuild是JDK1.5新增加的一个类,与StringBuffer具有相同的操作。

区别在于:StringBuffer是线程安全的类。StringBuild不是线程安全的类,在单线程中性能要比StringBuffrer高。

例如:《Think in Java》中,描述HashTable和HashMap区别一样,就是因为HashTable支持线程同步、保证线程安全而导致的性能下降。

  HashTable是线程安全的,很多方法都是synchronized方法。

  HashMap不是线程安全的,但在单线程程序中的性能比HashTable要高。

原文地址:https://www.cnblogs.com/mingluosunshan/p/3227484.html