- //StringBuffer类定义
- function StringBuffer() {
- this._strings = new Array;
- }
- StringBuffer.prototype.append = function (str) {
- this._strings.push(str);
- };
- StringBuffer.prototype.toString = function () {
- return this._strings.join(“”);
- };
- //test
- var buffer = new StringBuffer();
- buffer.append(“hello “);
- buffer.append(“world”);
- var result = 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.