首页 > 其他 > 详细

区别String、StringBuilder、Stringbuffer的总结

时间:2017-09-28 21:36:21      阅读:206      评论:0      收藏:0      [点我收藏+]

1.三者在执行速度上: StringBuilder > StringBuffer > String

2.  String:不可变长字符串

   StringBuilder : 为可变长字符串

   StringBuffer:为可变长字符串

示例一:String s = "this is a";
        System.out.println(s.hashCode());
        s = s + " apple.";
        System.out.println(s.hashCode());
        System.out.println(s);

乍一看,String类型的字符串,不是也可改变长度吗?实际上,这两个字符串s在内存中不是同一个对象,(hashCode码不一样),第二个s对象是jvm生成的对第一个s对象的拷贝.

3.String s = "this is "+"a simple "+"test";

StringBuilder sb = new StringBuilder("This is ").append("a simple ").append(test);

在这种情况下,貌似生成String字符串的速度比生成StringBuilder的速度要快,但实际上String s = "this is "+"a simple "+"test";本身就是String s = "this is a simple test".

所以不需要太多的时间了。但大家这里要注意的是,如果你的字符串是来自另外的String对象的话,速度就没那么快了,譬如:

    String str2 = “This is only a”;

    String str3 = “ simple”;

    String str4 = “ test”;

    String str1 = str2 +str3 + str4;

4. 线程安全方面:StringBuilder 线程不安全

        StringBuffer 线程安全的

在单线程操作大量数据时使用StringBuilder,多线程操作大量数据时使用StringBuffer。

 

区别String、StringBuilder、Stringbuffer的总结

原文:http://www.cnblogs.com/qjm575632320/p/7608650.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!