---
title: "定义JavaScript中的StringBuffer类"
author: "zwfc"
date: "2008-12-25T13:29:00Z"
tags: []
slug: "javascript-stringbuffer"
draft: false
lastmod: "2008-12-25T13:29:00Z"
id: 470944
url: "https://zwfc.iteye.com/blog/470944"
---

01. //StringBuffer类定义
02. functionStringBuffer(){
03. this.\_strings=newArray;
04. }
05. StringBuffer.prototype.append=function(str){
06. this.\_strings.push(str);
07. };
08. StringBuffer.prototype.toString=function(){
09. returnthis.\_strings.join(“”);
10. };
11. //test
12. varbuffer=newStringBuffer();
13. buffer.append(“hello“);
14. buffer.append(“world”);
15. 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.