1 String str="abc"+"de";
2 StringBuilder stringBuilder=new StringBuilder().append("abc").append("de");
3 System.out.println(str);
4 System.out.println(stringBuilder.toString());
String的速度却比StringBuilder的反应速度要快么?
有的人说是快,有的人说一样快,到底时怎么样的呢?
. class StringEqualTest {
public static void main(String[] args) {
String s1 = "Programming";
String s2 = new String("Programming");
String s3 = "Program";
String s4 = "ming";
String s5 = "Program" + "ming";
String s6 = s3 + s4;
System.out.println(s1 == s2); //false
System.out.println(s1 == s5); //true
System.out.println(s1 == s6); //false
System.out.println(s1 == s6.intern()); //true
System.out.println(s2 == s2.intern()); //false
}
那为什么System.out.println(s1 == s5);结果是true呢
应该是String s = "Program" + "ming";string比StringBuffer快;
String s1 = “Program”;
Strind s =s1+"ming";循环的话StringBuffer比String快吧
StringBuilder效率更高,但是更不安全。这个小例子看不出区别。你可以用循环测试一下
class StringEqualTest {
public static void main(String[] args) {
String s1 = "Programming";
String s2 = new String("Programming");
String s3 = "Program";
String s4 = "ming";
String s5 = "Program" + "ming";
String s6 = s3 + s4;
System.out.println(s1 == s2); //false
System.out.println(s1 == s5); //true
System.out.println(s1 == s6); //false
System.out.println(s1 == s6.intern()); //true
System.out.println(s2 == s2.intern()); //false
}
那为什么System.out.println(s1 == s5);结果是true呢
应该是String s = "Program" + "ming";string比StringBuffer快;
String s1 = “Program”;
Strind s =s1+"ming";循环的话StringBuffer比String快吧
@小鹰eagle: 没毛病,StringBuffer就是为了方便解决你说的第二种情况的
应该差不多吧,其实+号它底层实现也是new一个StringBuffer吧
class StringEqualTest {
public static void main(String[] args) {
String s1 = "Programming";
String s2 = new String("Programming");
String s3 = "Program";
String s4 = "ming";
String s5 = "Program" + "ming";
String s6 = s3 + s4;
System.out.println(s1 == s2); //false
System.out.println(s1 == s5); //true
System.out.println(s1 == s6); //false
System.out.println(s1 == s6.intern()); //true
System.out.println(s2 == s2.intern()); //false
}
那为什么System.out.println(s1 == s5);结果是true呢
应该是String s = "Program" + "ming";string比StringBuffer快;
String s1 = “Program”;
Strind s =s1+"ming";循环的话StringBuffer比String快吧
@小鹰eagle: s1与s2不相等是因为它们所在内存位置不同,一个在方法区的常量池里,一个在堆中,
s1和s5相等是因为s5它的生成过程中在常量池中发现内容一样的字符串(Programming)它就在把s5直接指向了这个(Programming)。
StringBuffer和String谁快的问题,我个人认为在操作字符串相加操作上速度是差不多的,但是StringBuffer会在append上加锁,这个也会占用时间的,但是对于很多append操作,jvm会做一些优化就是锁粗化,多个append只会在第一个加锁,在最后一个解锁,降低加锁解锁的消耗。
以上都只是个人理解!
直接上代码你就知道了:
String str1 = "";
for (int i = 0; i < 100000; i++) {
str1 = str1 + ",java";
}
StringBuilder是StringBuffer的非线程安全版,效率大概差1倍的样子。
StringBuffer sb1 = new StringBuffer();
for (int i = 0; i < 10000000; i++) {
sb1.append(",java");
}
上面的代码运行很慢,分析可以到我博客看看。