- //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.