- //StringBuffer类定义
- functionStringBuffer(){
- this._strings=newArray;
- }
- StringBuffer.prototype.append=function(str){
- this._strings.push(str);
- };
- StringBuffer.prototype.toString=function(){
- returnthis._strings.join(“”);
- };
- //test
- varbuffer=newStringBuffer();
- buffer.append(“hello“);
- buffer.append(“world”);
- varresult=buffer.toString();
使用StringBuffer拼接字符串比用String效率高。
考虑下面一段代码的运行。
var str = “hello “;
str += “world”;
This code actually executes the following steps behind the scenes:
1. Create a string to store “hello “.
2. Create a string to store “world”.
3. Create a string to store the result of concatenation.
4. Copy the current contents of str into the result.
5. Copy the “world” into the result.
6. Update str to point to the result.
本文介绍使用StringBuffer类优化字符串拼接操作的方法,并通过示例对比了直接使用String进行拼接的效率问题。了解StringBuffer如何减少内存中创建额外字符串副本的过程。
834

被折叠的 条评论
为什么被折叠?



