前言:
String: String类还有String类的属性都是被final修饰的,每次对象改变时相当于指向了一个新的对象,所以性能最差
StringBuilder:属于可变字符串,比String快很多,可以用toString()方法转成String对象
StringBuffer: 属于线程安全的可变字符串,方法前面都加了synchronized,当然在单线程中推荐用StringBuilder,性能快很多
当然,速度不是绝对的
String s1= "a"+"b"+"c";要比 new StringBuilder().append("a").append("b").append("c")要快,jvm会当作String s1="abc"来直接处理。
代码:
package com.xhx.java;
import org.junit.Test;
/**
* xuhaixing
* 2018/6/28 21:07
**/
public class TestStringAndBufferAndBuilder {
/**
* 内部在执行是new StringBuiler 然后append,然后toString 所以是最慢的
*/
@Test
public void testString(){
long begin = System.currentTimeMillis();
String str ="";
for(int i = 0;i<50000;i++){
str+="hello";
}
long end = System.currentTimeMillis();
System.out.println(end-begin); //8499
}
/**
* 最快的
*/
@Test
public void testBuilderString(){
long begin = System.currentTimeMillis();
StringBuilder str =new StringBuilder();
for(int i = 0;i<500000;i++){
str.append("hello");
}
long end = System.currentTimeMillis();
System.out.println(end-begin); //47
}
/**
* 线程安全的,第二快
*/
@Test
public void testBufferString(){
long begin = System.currentTimeMillis();
StringBuffer str =new StringBuffer();
for(int i = 0;i<500000;i++){
str.append("hello");
}
long end = System.currentTimeMillis();
System.out.println(end-begin); //78
}
}