String不适合做字符串拼接,每次会new新对象,效率最低,StringBuffer和StringBuilder效率高,StringBuffer线程安全,速度相对慢,用的少,只有在考虑线程问题时才使用。StringBuilder线程不安全,速度看,用的多。例:
public class StringStringBuilderStringBuffer { int count=1000; public static void testString(){ Long start=System.currentTimeMillis(); String s=""; for(int i=0;i<count;i++){ s+="testString"+i; } Long end=System.currentTimeMillis(); System.out.println("testString count---"+(end-start)); } public static void testStringBuffer(){ Long start=System.currentTimeMillis(); StringBuffer sb=new StringBuffer(); for(int i=0;i<count;i++){ sb.append("testString"+i); } Long end=System.currentTimeMillis(); System.out.println("testStringBuffer count---"+(end-start)); } public static void testStringBuilder(){ Long start=System.currentTimeMillis(); StringBuilder sb = new StringBuilder(); for(int i=0;i<count;i++){ sb.append("testStringBuilder"+i); } Long end=System.currentTimeMillis(); System.out.println("testStringBuilder count---"+(end-start)); } public static void main(String[] args) { testString(); testStringBuffer(); testStringBuilder(); } }
运行结果:
1、当count=1000:
testString count---22 testStringBuffer count---3 testStringBuilder count---2
2、当count=10000:
testString count---1461 testStringBuffer count---6 testStringBuilder count---2
3、当count=100000:
testString count---178333 testStringBuffer count---68 testStringBuilder count---23
时间: 2024-10-06 01:04:45