javase 复习汇总一:strignbuilder += +效率比较

package Test2;


public class test1{

public static void main(String [] args){

String text = "";

long beginTime = System.currentTimeMillis();

for(int i = 0; i < 10000; i++){

text +i;

}

long endTime = System.currentTimeMillis();

System.out.println("Running time:" + (endTime - beginTime));

StringBuilder builder = new StringBuilder("");

beginTime = System.currentTimeMillis();

for(int i = 0; i < 10000; i++){

builder.append(String.valueOf(i));

}

endTime = System.currentTimeMillis();

System.out.println("Runing time:" + (endTime - beginTime));

String txt2="";

beginTime = System.currentTimeMillis();

for(int i = 0; i < 10000; i++){

txt2=txt2+i;

}

endTime = System.currentTimeMillis();

System.out.println("Runing time:" + (endTime - beginTime));

}

}

Running time:370

Runing time:5

Runing time:197

证明 Stringbuilder >"+">"+=" 

还有一个 x++,x=x+1 ,x+=1 

x=x+1 要寻址两次,时间最长 

x+= 

寻找x的地址,然后读取地址中x的值,再在寄存器中将x的值加1,接着将计算结果存到x的地址中(这里计算机知道读与写两个操作的地址是相同的)
x++ 寻找x的地址,然后读取地址中x的值,然后直接将地址中的值加1


你可能感兴趣的:(StringBuilder,+,+=)