1.新创建一个对象 long startTimeA = System.currentTimeMillis(); StringBuilder sb = null;
for (int i = 1; i <= 10000000; i++) {
sb = new StringBuilder();
sb.append(“1”);
String a = sb.toString();
} this.newProject = System.currentTimeMillis() – startTimeA; 2.删除字符串 long startTimeB = System.currentTimeMillis(); for (int i = 1; i <= 10000000; i++) { sb.delete(0, sb.length()); sb.append(“2”); String a = sb.toString(); } this.delete = System.currentTimeMillis() – startTimeB; 3.设置长度 long startTimeC = System.currentTimeMillis(); for (int i = 1; i <= 10000000; i++) { sb.setLength(0); sb.append(“3”); String a = sb.toString(); } this.updateLength = System.currentTimeMillis() – startTimeC; 运行结果:newProject:168046delete:95123updateLength:93593 结论:可以明显看出,重新创建对象的方法是最慢的,删除字符串和设置长度的方法差别不大.