String链接性能的问题一直是比较基础也是大家比较容易出错和迷惑的问题,在这里就通过几段代码和反编译的代码来详细的介绍一下String链接性能的问题。
第一种情况: 字符串直接赋值常量,然后进行链接。
原始代码
public class test{
public static void main(String[] args){
String s = "hello";
String t = "world";
String r = "!!";
String str = s + t + r;
}
}
反编译之后的代码
public class test
{
public test()
{
}
public static void main(String args[])
{
String s = "hello";
String s1 = "world";
String s2 = "!!";
String s3 = (new StringBuilder()).append(s).append(s1).append(s2).toString();
}
}
显而易见,字符串连接时是创建了一个StringBuilder,然后进行append操作,这样的好处众所周知:不需要创建过多String的对象(String不可变性),因此效率出众,而且StringBuilder非同步,所以比StringBuffer效率更高。
第二种情况:String对象通过new得到
原始代码
public class test{
public static void main(String[] args){
String s = new String("Hello");
String t = new String("world");
String r = new String("!!");
String str = s + t + r;
}
}
反编译后的代码:
public class test
{
public test()
{
}
public static void main(String args[])
{
String s = new String("Hello");
String s1 = new String("world");
String s2 = new String("!!");
String s3 = (new StringBuilder()).append(s).append(s1).append(s2).toString();
}
}
这和第一种反编译出来的代码一致,所以从此看出,这样写效率也是极高的,那么什么情况下会出现字符串链接低效的情况呢?看下面第三种情况:
原始代码
public class test{
public static void main(String[] args){
String str = new String("Hello ");
String temp = new String("world ");
for(int i = 0; i < 100; i++){
str = str + temp ;
}
}
}
反编译后的代码
public class test
{
public test()
{
}
public static void main(String args[])
{
String s = new String("Hello ");
String s1 = new String("world ");
for(int i = 0; i < 100; i++)
s = (new StringBuilder()).append(s).append(s1).toString();
}
}
创建了100次StringBuilder这样效率必定也是用String链接一样,所以效率不高