StringBuilder的性能

Posted on 2020-02-26 22:30  wzhw2015  阅读(111)  评论(0编辑  收藏  举报
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:168046
delete:95123
updateLength:93593
 
结论:可以明显看出,重新创建对象的方法是最慢的,删除字符串和设置长度的方法差别不大.

Copyright © 2024 wzhw2015
Powered by .NET 9.0 on Kubernetes