作者:crazy82071 | 来源:互联网 | 2024-10-19 16:52
String、StringBuffer和StringBuilder都是Java中用来表示字符串的。在Java中,String类是一个不可变类,任何对String的改变都会引发新的String对象的生成。StringBuffer和StringBuilder则都是可变类,任何对他所指代的字符串都不会产生新的对象。StringBuilder是Java5后提出来的,与StringBuffer相比,StringBuilder有更高的执行效率,但其不是线程安全的。
1. 性能对比
下面对String,StringBuffer和StringBuilder进行append操作的性能对比。主要比对代码如下:
public static void compareAddTime(String string,StringBuilder stringBuilder,StringBuffer stringBuffer){long preTime,afterTime;preTime &#61; System.currentTimeMillis();for(int i &#61; 0;i <100000; &#43;&#43;i){string &#61; string &#43; &#39;a&#39;;}afterTime &#61; System.currentTimeMillis();System.out.println("String操作10000遍需要时长为:" &#43; (afterTime - preTime) &#43; "ms");preTime &#61; System.currentTimeMillis();for(int i &#61; 0;i <10000000; &#43;&#43;i){stringBuffer.append(&#39;a&#39;);}afterTime &#61; System.currentTimeMillis();System.out.println("StringBuffer操作1000000000遍需要时长为:" &#43; (afterTime - preTime) &#43; "ms");preTime &#61; System.currentTimeMillis();for(int i &#61; 0;i <10000000; &#43;&#43;i){stringBuilder.append(&#39;a&#39;);}afterTime &#61; System.currentTimeMillis();System.out.println("StringBuilder操作1000000000遍需要时长为:" &#43; (afterTime - preTime) &#43; "ms");}
执行以上方法&#xff0c;得出如下结果图&#xff1a;
由于String每次" &#43; “操作都要new新对象&#xff0c;因此仅” &#43; "10000次&#xff0c;否则容易内存溢出。我们可以看见&#xff0c;String具有最低的性能效率&#xff0c;在相同数量级下StringBuilder操作效率要高于StringBuilder&#xff0c;且当其数量级越高&#xff0c;差距越明显。因此在实际中我们应该尽量少用String对字符串进行操作&#xff0c;不仅效率低下&#xff0c;还容易导致频繁垃圾回收&#xff0c;影响代码效率。
1.1 String " &#43; "操作具体实现
为了更直观查看String是如何new新对象的&#xff0c;我对String进行了以下探索&#xff1a;
public static void main(String[] args){String string &#61; new String();string &#61; string &#43; "abc";}
针对如上简单的" &#43; "操作&#xff0c;使用javac指令对其进行编译&#xff0c;并使用javap -c指令对其进行反编译。得到如下结果
Code:0: new #2 // class java/lang/String3: dup4: invokespecial #3 // Method java/lang/String."":()V7: astore_18: new #4 // class java/lang/StringBuilder11: dup12: invokespecial #5 // Method java/lang/StringBuilder."":()V15: aload_116: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;19: ldc #7 // String abc21: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;24: invokevirtual #8 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;27: astore_128: return
我们可以看到&#xff0c;当进行" &#43; "操作时&#xff0c;Java会先new一个新的StringBuilder对象&#xff0c;并对其进行append操作&#xff0c;最后返回toString()字符串。反应到Java代码&#xff0c;即为如下过程:
new StringBuilder().append(string).append("abc").toString()
1.2 StringBuffer和StringBuilder类append操作对比
针对StringBuffer和StringBuilder&#xff0c;我们可以查看他们的实现方式。
//StringBuffer的append方法
&#64;Override
public synchronized StringBuffer append(String str) {toStringCache &#61; null;super.append(str);return this;
}//StringBuilder的append方法
&#64;Override
public StringBuilder append(String str) {super.append(str);return this;
}
如上所示&#xff0c;在StringBuffer中&#xff0c;使用了synchronized保证其线程安全性。此外在StringBuffer中有一个toStringCache数组&#xff0c;用以缓存StringBuffer对象toString后结果。当StringBuffer发生修改了字符串的操作时&#xff0c;需要把缓存清除。
StringBuffer和StringBuilder均继承了AbstractStringBuilder类&#xff0c;因此他们的append方法均一致。查看其append实现方法&#xff0c;其实现代码如下所示&#xff1a;
public AbstractStringBuilder append(String str) {if (str &#61;&#61; null)return appendNull();int len &#61; str.length();//判断是否有足够空间存储str&#xff0c;若不足&#xff0c;触发扩容ensureCapacityInternal(count &#43; len);str.getChars(0, len, value, count);count &#43;&#61; len;return this;
}
可以看到在append其&#xff0c;需要判断类对象是否有充足空间&#xff0c;是否需要扩容。其基本逻辑与ArratList和LinkedList类似(想了解更多关于ArrayList和LinkedList&#xff0c;可以看Java基础(一)-ArrayList和LinkedList性能对比与原因探索)。他们均有一个最大值MAX_ARRAY_SIZE(即Integer.MAX_VALUE - 8&#xff0c;为何要减8在ArrayList中阐述&#xff0c;这里不在解释)&#xff0c;当容量不足时进行扩容:
private int newCapacity(int minCapacity) {// overflow-conscious codeint newCapacity &#61; (value.length <<1) &#43; 2;if (newCapacity - minCapacity <0) {newCapacity &#61; minCapacity;}//若扩容后容量大于MAX_ARRAY_SIZE或者int已溢出&#xff0c;则把预留的 - 8位也用于数组&#xff0c;此时可能导致内存溢出return (newCapacity <&#61; 0 || MAX_ARRAY_SIZE - newCapacity <0)? hugeCapacity(minCapacity): newCapacity;
}
可以看到其扩容机制为原有长度 * 2 &#43; 2&#xff08;这里 &#43; 2应该是避免0 * 2仍是0导致的无法扩容情况&#xff09;&#xff0c;若仍不足&#xff0c;扩容到需要的最小长度minCapacity。若扩容后容量大于MAX_ARRAY_SIZE或者int已溢出&#xff0c;则把预留的 - 8位也用于数组&#xff0c;此时可能导致内存溢出。
2. 线程安全性对比
我们可以看到&#xff0c;在StringBuffer中用synchronized保证了线程安全&#xff0c;在StringBuilder中则没有。且String每次都会生成新对象。这里编写代码测试他们的线程安全性&#xff1a;
AppendThread类&#xff1a;
用于对StringBuffer&#xff0c;StringBuilder&#xff0c;String进行append操作的线程类。
package com.thread.demo.string;public class AppendThread extends Thread{private StringBuffer stringBuffer;private StringBuilder stringBuilder;private String string;public AppendThread(StringBuffer stringBuffer,StringBuilder stringBuilder,String string){this.stringBuffer &#61; stringBuffer;this.stringBuilder &#61; stringBuilder;this.string &#61; string;}&#64;Overridepublic void run(){for(int i &#61; 0;i <1000; &#43;&#43;i){stringBuffer.append("a");stringBuilder.append("a");string &#61; string &#43; "a";}System.out.println("StringBuffer Size:" &#43; stringBuffer.length() &#43; " | " &#43; "StringBuilder Size:" &#43; stringBuilder.length() &#43; " | " &#43; "String Size:" &#43; string.length());}
}
Main方法&#xff1a;
new十个新线程&#xff0c;同步append。
package com.thread.demo.string;public class stringCompare {public static void main(String[] args){StringBuffer stringBuffer &#61; new StringBuffer();StringBuilder stringBuilder &#61; new StringBuilder();String string &#61; new String();//测试运行时间//compareAddTime(string,stringBuilder,stringBuffer);//string &#61; string &#43; "abc";//验证线程安全性for(int i &#61; 0;i <10; &#43;&#43;i){new AppendThread(stringBuffer,stringBuilder,string).start();}}/*** &#64;Description 查看String&#xff0c;StringBuilder和StringBuffer操作时长* &#64;author Sc_Cloud* &#64;param * &#64;param string* &#64;param stringBuilder* &#64;param stringBuffer* &#64;return void* &#64;date 2022/4/8 19:44*/public static void compareAddTime(String string,StringBuilder stringBuilder,StringBuffer stringBuffer){long preTime,afterTime;preTime &#61; System.currentTimeMillis();for(int i &#61; 0;i <100000; &#43;&#43;i){string &#61; string &#43; &#39;a&#39;;}afterTime &#61; System.currentTimeMillis();System.out.println("String操作10000遍需要时长为:" &#43; (afterTime - preTime) &#43; "ms");preTime &#61; System.currentTimeMillis();for(int i &#61; 0;i <10000000; &#43;&#43;i){stringBuffer.append(&#39;a&#39;);}afterTime &#61; System.currentTimeMillis();System.out.println("StringBuffer操作1000000000遍需要时长为:" &#43; (afterTime - preTime) &#43; "ms");preTime &#61; System.currentTimeMillis();for(int i &#61; 0;i <10000000; &#43;&#43;i){stringBuilder.append(&#39;a&#39;);}afterTime &#61; System.currentTimeMillis();System.out.println("StringBuilder操作1000000000遍需要时长为:" &#43; (afterTime - preTime) &#43; "ms");}
}
正常情况下十个线程append1000次&#xff0c;长度应该为10000。实际执行效果如下&#xff1a;
可以看到StringBuffer最大值为10000&#xff0c;StringBuilder最大值小于10000&#xff0c;String由于每次需要new新对象&#xff0c;因此长度均为单个线程append长度1000&#xff0c;符合预期。
总结
因此&#xff0c;对String、StringBuffer和StringBuilder&#xff0c;我们一般有如下结论&#xff1a;
- String在对字符串进行操作时会生成新的对象&#xff1b;
- StringBuffer和StringBuilder会操作原有对象&#xff0c;减少新生成对象&#xff1b;
- StringBuffer是线程安全的&#xff0c;效率低&#xff1b;
- StringBuilder不是线程安全的&#xff0c;但是执行效率高&#xff1b;
由于StringBuilder相较于StringBuffer有速度优势&#xff0c;因此多数情况下建议使用StringBuilder