jvm在处理字符串拼接符号+时,是用StringBuilder(jdk>=1.5)/StringBuffer(jdk<=1.4)实现的。网上常见的是不要用+号要用StringBuilder的观点 ,理由是认为下面这段代码有性能差异:
String st1 = "hello" + "world"; StringBuild sb = new StringBuilder("hello");
sb.append("world");
String st2 =Sb.toString();
网上的观点认为,用加号的虽然用了StringBuilder来实现,但构造了两个临时的String对象hello和world,1个临时的StringBuilder对象,1个最终的helloworld对象,而用StringBuilder的只用了一个StringBuilder对象和1个helloworld对象。
但我认为,就上面的例子,hello和world都是编译时常量,只会分配一次内存,不存在新建临时String对象一说,所以用+号和用StringBuilder性能是一样的,+号还少写点代码。单就两个字符串拼接来说, 不管是用+号,还是用StringBuilder的构造和append方法,都是预先要有两个String对象的,所以性能肯定是一样的。而如果jvm没对+号做优化,在大于两个字符串拼接时,如"hello"+"world"+"ni"+"hao",会多生成"helloworld","helloworldni"这两个临时对象,用StringBuilder就有必要了。而平常就两个字符串拼接而言,用+号即可,我的理解对么?请指教
String st1 = "hello" + "world"; StringBuild sb = new StringBuilder("hello");
sb.append("world");
String st2 =Sb.toString();
网上的观点认为,用加号的虽然用了StringBuilder来实现,但构造了两个临时的String对象hello和world,1个临时的StringBuilder对象,1个最终的helloworld对象,而用StringBuilder的只用了一个StringBuilder对象和1个helloworld对象。
但我认为,就上面的例子,hello和world都是编译时常量,只会分配一次内存,不存在新建临时String对象一说,所以用+号和用StringBuilder性能是一样的,+号还少写点代码。单就两个字符串拼接来说, 不管是用+号,还是用StringBuilder的构造和append方法,都是预先要有两个String对象的,所以性能肯定是一样的。而如果jvm没对+号做优化,在大于两个字符串拼接时,如"hello"+"world"+"ni"+"hao",会多生成"helloworld","helloworldni"这两个临时对象,用StringBuilder就有必要了。而平常就两个字符串拼接而言,用+号即可,我的理解对么?请指教
String str = "hello" + "world";
}{ // 块2
StringBuffer buffer = new StringBuffer("hello");
buffer.append("world");
String str = buffer.toString();
}{ // 块3
String str = new String("hello");
str += "world";
}在JDK5.0环境下,块1的性能远高于块2,块2的性能稍高于块3。
因为JDK5.0对String的+操作进行了优化。可用javap -c测试上述各块
so:string+string和stringbuffer.append一样的效果老版本jre例外
就从你提供的代码来说,的确是一样的效果
但是,业务没有这么简单,这里String st1 = "hello" + "world";是同时在编译期就被整合了,但是通常的业务都会有循环增加和替换
比如:
String temp="hello"+"world";
for(int x=0;x<100;x++){
temp=temp+x;
}
这种情况下,效率和空间占用就完全不一样了。当然,我们也应该就事论事,就lz这种情况来说,编译器的确是等同处理的
数量大的话 StringBuilder 的优点就出来了
public class Test {
public static void main(String args[]) {
String str1 = "hello" + "world";
String str2="helloworld";
System.out.println(str1==str2);
}
}
结果是什么?
public class Test {
public static void main(String args[]) {
String str1 = "hello" + "world";
String str2="helloworld";
System.out.println(str1==str2);
}
}结果是什么
import java.util.Date;public class Test {
public static void main(String args[]) {
long t1=new Date().getTime();
for(int i=0;i<10000000;i++){
String st1 = "hello" + "world";
}
long t2=new Date().getTime();
for(int j=0;j<10000000;j++){
StringBuilder sb = new StringBuilder("hello");
sb.append("world");
String st2 = sb.toString();
}
long t3=new Date().getTime();
System.out.println(t2-t1);
System.out.println(t3-t2);
}
}
这个可能会输出什么??
2953
第一个差值不管怎么做都是0,这个优化....
我举的例子不合适,应该
String st1 = "hello" ;
st1 += "world";这样就合时了