您的位置:首页 > 产品设计 > UI/UE

StringBuild 与 String 进行字符串相加性能比较

2017-06-10 23:11 302 查看
package com.company;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Main {

public static void main(String[] args) {
int n  =  1000;
long start = System.currentTimeMillis();
try {
TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<String> list = new ArrayList<>();
String s = "";
for (int i = 0; i < n; i++) {
s += i;
list.add(s);
}
System.out.println(list.get(0) == list.get(1)); //false
long end = System.currentTimeMillis();
System.out.println("String [" + (end - start) + "ms]");

try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}

StringBuilder sb = new StringBuilder();
List<StringBuilder> listSb = new ArrayList<>();

start = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
sb.append(i);
listSb.add(sb);
}
System.out.println(listSb.get(0) == listSb.get(1)); //true
end = System.currentTimeMillis();
System.out.println("StringBuilder [" + (end - start) + "ms]");

try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//速度 10000 300:1
//    100000 23847ms:4ms
//    1000000 执行好久:107ms

//因为 string在新加的时候会new String()操作  秒升500M内存
//从堆可以查看出来
// StringBuild 每一次增加的时候是内存之间的拷贝
// 源码 System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string