编写一个Java程序,对String、StringBuffer和StringBuilder进行性能测试。例如,模拟在循环中多次拼接字符串的操作。
时间: 2024-11-06 15:20:01 浏览: 11
在Java中,String是一个不可变的对象,而StringBuilder和StringBuffer则是可变的。为了测试它们在大量字符串拼接操作下的性能差异,你可以编写如下的简单程序:
```java
public class StringPerformanceTest {
public static void main(String[] args) {
int iterations = 100000; // 迭代次数,可以调整以观察更细致的性能差异
long startTime = System.currentTimeMillis(); // 开始时间标记
// 使用String
for (int i = 0; i < iterations; i++) {
String str = "";
for (int j = 0; j < 100; j++) {
str += "test";
}
}
long endTimeString = System.currentTimeMillis() - startTime;
// 使用StringBuilder
StringBuilder stringBuilder = new StringBuilder();
startTime = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
for (int j = 0; j < 100; j++) {
stringBuilder.append("test");
}
}
long endTimeStringBuilder = System.currentTimeMillis() - startTime;
// 使用StringBuffer,由于线程安全,这里需要同步上下文
StringBuffer stringBuffer = new StringBuffer();
synchronized (stringBuffer) {
startTime = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
for (int j = 0; j < 100; j++) {
stringBuffer.append("test");
}
}
}
long endTimeStringBuffer = System.currentTimeMillis() - startTime;
System.out.println("With String:");
System.out.println("Time taken: " + endTimeString + "ms");
System.out.println("With StringBuilder:");
System.out.println("Time taken: " + endTimeStringBuilder + "ms");
System.out.println("With StringBuffer (synchronized):");
System.out.println("Time taken: " + endTimeStringBuffer + "ms");
// 相关问题:
阅读全文