如何写代码比较性能

来源:百度知道 编辑:UC知道 时间:2024/05/22 12:50:51
String a = "";
a = a+"123";

StringBuffer b = new StringBuffer();
b.append("123");

写一段可运行的代码,比较两者的性能,要求有具体可比较的数据

public static void main(String[] args) throws InterruptedException {
System.out.println("测试开始了...");

// String测试
String s = "";
long oneStartTime = System.currentTimeMillis();
for(int i = 0; i < 5000; i++) {
s += "a";
}
long oneResult = System.currentTimeMillis() - oneStartTime;
System.out.println("String性能测试结果:" + oneResult + " 毫秒。");

// StringBuffer测试
StringBuffer sb = new StringBuffer();
long twoStartTime = System.currentTimeMillis();
for(int i = 0; i < 5000; i++) {
sb.append("a");
}
long twoResult = System.currentTimeMillis() - twoStartTime;
System.out.println("StringBuffer性能测试结果:" + twoResult + "毫秒。");

Syst