Java中测试StringBuilder、StringBuffer、String在字符串拼接上的性能

时间:2021-07-21 09:27:08

应一个大量字符串拼接的任务

测试一下StringBuilder、StringBuffer、String在操作字符串拼接时候的性能

性能上理论是StringBuilder  >  StringBuffer  >  String

测试方法:

创建一个StirngTest类含有静态常量字符串是26个字母,以及一个循环轮数

在测试时采用循环来操作字符串的拼接,计算操作时间并输出:

package com.test.xlc;

import java.util.Random;

public class StringTest {

    static final String strFinal = "abcdefghijklmnopqrstovwxyz";
static final int forInt = 100; static void StringBuilderTest() { Random rand = new Random(47);
StringBuilder strB = new StringBuilder();
long start = System.currentTimeMillis();
for(int i = 0; i < forInt; ++i) {
int randInt = rand.nextInt(23);
strB.append(strFinal.substring(randInt, randInt + 4));
}
long end = System.currentTimeMillis();
// System.out.println(strB.toString());
System.out.println("StringBuilderTest:" + (end - start));
} static void StringBufferTest() {
Random rand = new Random(47);
StringBuffer strB = new StringBuffer();
long start = System.currentTimeMillis();
for(int i = 0; i < forInt; ++i) {
int randInt = rand.nextInt(23);
strB.append(strFinal.substring(randInt, randInt + 4));
}
long end = System.currentTimeMillis();
// System.out.println(strB.toString());
System.out.println("StringBufferTest:" + (end - start));
} static void StringOnly() {
Random rand = new Random(47);
String str = "";
long start = System.currentTimeMillis();
for(int i = 0; i < forInt; ++i) {
int randInt = rand.nextInt(23);
str += strFinal.substring(randInt, randInt + 4);
}
long end = System.currentTimeMillis();
// System.out.println(str);
System.out.println("String:" + (end - start));
} public static void main(String...args) {
StringBuilderTest();
StringBufferTest();
StringOnly(); }
}

测试循环次数:

100

StringBuilderTest:0
StringBufferTest:0
String:0

1000

StringBuilderTest:1
StringBufferTest:0
String:7

10000

StringBuilderTest:2
StringBufferTest:2
String:217

100000

StringBuilderTest:12
StringBufferTest:10
String:17136

1000000

StringBuilderTest:55
StringBufferTest:53
我提前终止了

之后我又测试了拼接长串,本实验结果显示在拼接字符串的效率上:

StringBuffer  >    StringBuilder  >  String