StringBuilder的append()效率比String的+运算符效率高太多

来源:互联网 发布:开源游戏服务器源码 编辑:程序博客网 时间:2024/05/18 20:05
public static void main(String[] args) { // TODO 自动生成的方法存根 String str = ""; StringBuffer sb = new StringBuffer(); long start = 0L; long end = 0L; start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { str = str + "a"; } end = System.currentTimeMillis(); System.out.println("使用string的时间是:" + (end - start) + "毫秒!"); start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { sb.append("a"); } end = System.currentTimeMillis(); System.out.println("使用StringBuffer的时间是:" + (end - start) + "毫秒!"); //System.out.println(getMax("aba")); } 使用string的时间是:4471毫秒!使用StringBuffer的时间是:3毫秒!这完全不是在一个层次上,希望各位谨记!大量字符串连接一定要用append()方法,原因呢其实很简单,字符串连接每次都需要创建新的字符串对象来保存新串
0 0
原创粉丝点击