Java中String和StringBuffer对于拼接运算中效率的对比
String类型在java中是immutable,意思就是不可变的,每次对String进行拼接操作,实际在jvm中都是new了一个新的String,随着String的new的次数越多,会造成虚拟机速度下降。
StringBuffer的内部实际是一个字符数组,对于不同的jdk可以使用以下方法查看其实际的大小和容量(请参考下面的代码),注意:这是两个不同的概念,具体请参考API的文档。
String str1 = "redpig";
StringBuffer sb = new StringBuffer(str1);
System.out.println(sb.length()); //内容长度
System.out.println(sb.capacity());//总空间
如果每次随机生成10个字符(仅限于大小写字母和数字),重复10000次,此时可以清楚看到String和StringBuffer的运行效率。
import java.util.Random;
public class TestStrAndStrBuf {
private static char[] characterPool = new char[62];
static {
char c = 0;
int i = 0;
for (c = 'a'; c < 'z'; c++, i++)
characterPool[i] = c;
for (c = 'A'; c < 'Z'; c++, i++)
characterPool[i] = c;
for (c = '0'; c < '9'; c++, i++)
characterPool[i] = c;
}
public static void main(String[] args) {
appendString(10000, 10);
appendStringBuffer(10000, 10);
}
public static char[] getRandomCharacters(int charactersLength) {
char[] chars = new char[charactersLength];
Random r = new Random();
for (int i = 0; i < charactersLength; i++)
chars[i] = characterPool[Math.abs(r.nextInt()) % characterPool.length];
return chars;
}
public static void appendString(int times, int charactersLength) {
String string = new String();
long startTime = System.currentTimeMillis();
for (int i = 0; i < times; i++)
string += String.valueOf(getRandomCharacters(charactersLength));
long endTime = System.currentTimeMillis();
System.out.println("Run time is " + (endTime - startTime));
}
public static void appendStringBuffer(int times, int charactersLength) {
StringBuffer stringBuffer = new StringBuffer();
long startTime = System.currentTimeMillis();
for (int i = 0; i < times; i++)
stringBuffer.append(getRandomCharacters(charactersLength));
long endTime = System.currentTimeMillis();
System.out.println("Run time is " + (endTime - startTime));
}
}
不同的硬件和软件运行出来的结果有所区别,本机中的效果如下:
所以,针对字符频繁改动的应用中,请使用StringBuffer!