string &stringBuilder & stringBuffer
2016-06-11 22:10
330 查看
string每次内容发生改变时,都会生成一个新的string对象,然后指针再指向新的string对象;
stringBuffer每次改变时都是对对象本身进行操作。字符串变量。线程安全。主要操作是 append
和 insert 方法
StringBuilder 字符串变量。非线程安全。主要操作:添加(在尾部添加):append();删除:deleteCharAt().
因此,当字符串内容经常改变时,最好使用stringBuffer。
而在某些特别情况下, String 对象的字符串拼接其实是被 JVM 解释成了 StringBuffer 对象的拼接,所以这些时候 String 对象的速度并不会比 StringBuffer 对象慢,而特别是以下的字符串对象生成中, String 效率是远要比 StringBuffer 快的:
String S1 = “This is only a” + “ simple” + “ test”;
StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);
你会很惊讶的发现,生成 String S1 对象的速度简直太快了,而这个时候 StringBuffer 居然速度上根本一点都不占优势。其实这是 JVM 的一个把戏,在 JVM 眼里,这个
String S1 = “This is only a” + “ simple” + “test”; 其实就是:
String S1 = “This is only a simple test”; 所以当然不需要太多的时间了。但大家这里要注意的是,如果你的字符串是来自另外的 String 对象的话,速度就没那么快了,譬如:
String S2 = “This is only a”;
String S3 = “ simple”;
String S4 = “ test”;
String S1 = S2 +S3 + S4;
这时候 JVM 会规规矩矩的按照原来的方式去做
在大部分情况下 StringBuffer > String
在大部分情况下 StringBuilder > StringBuffer
stringBuffer每次改变时都是对对象本身进行操作。字符串变量。线程安全。主要操作是 append
和 insert 方法
StringBuilder 字符串变量。非线程安全。主要操作:添加(在尾部添加):append();删除:deleteCharAt().
因此,当字符串内容经常改变时,最好使用stringBuffer。
而在某些特别情况下, String 对象的字符串拼接其实是被 JVM 解释成了 StringBuffer 对象的拼接,所以这些时候 String 对象的速度并不会比 StringBuffer 对象慢,而特别是以下的字符串对象生成中, String 效率是远要比 StringBuffer 快的:
String S1 = “This is only a” + “ simple” + “ test”;
StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);
你会很惊讶的发现,生成 String S1 对象的速度简直太快了,而这个时候 StringBuffer 居然速度上根本一点都不占优势。其实这是 JVM 的一个把戏,在 JVM 眼里,这个
String S1 = “This is only a” + “ simple” + “test”; 其实就是:
String S1 = “This is only a simple test”; 所以当然不需要太多的时间了。但大家这里要注意的是,如果你的字符串是来自另外的 String 对象的话,速度就没那么快了,譬如:
String S2 = “This is only a”;
String S3 = “ simple”;
String S4 = “ test”;
String S1 = S2 +S3 + S4;
这时候 JVM 会规规矩矩的按照原来的方式去做
在大部分情况下 StringBuffer > String
在大部分情况下 StringBuilder > StringBuffer
相关文章推荐
- LeetCode-128.Longest Consecutive Sequence
- JAVA UUID
- UE4杂记
- STL中deque详解及与vector和list的区别
- finished with non-zero exit value 2
- UIScrollView&UIPageControl的使用
- leetcode 300. Longest Increasing Subsequence
- AS Bug:Error:failed to find Build Tools revision 24.0.0 rc1
- Multiple actions were found that match the request
- Android常用的Uiutl
- AndroidStudio创建项目时一直处于building“project name”gradle project info的解决办法
- 去除[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platfor
- [javaSE] GUI(鼠标事件)
- 【颗粒归仓】(四)代码走查--在MSBuild上集成StyleCop的配置
- GUID
- IBM Bluemix IoT Platform 创建设备和API密钥
- perl多线程rsync备份文件到远端主机
- IOS UIDevice & IOS检测屏幕旋转实例
- 编写函数返回值value的二进制模式从左到右翻转后的值
- IOS UITableView单元点击事件