js实现stringbuffer
在JavaScript中,没有内置的StringBuffer类,但可以通过数组或字符串拼接的方式模拟类似功能。以下是几种实现方法:

使用数组和join方法
数组的push方法可以高效地追加字符串片段,最后通过join方法合并成完整字符串。这种方式在频繁拼接大量字符串时性能较好。

function StringBuffer() {
this.buffer = [];
}
StringBuffer.prototype.append = function(str) {
this.buffer.push(str);
return this;
};
StringBuffer.prototype.toString = function() {
return this.buffer.join('');
};
// 使用示例
const sb = new StringBuffer();
sb.append('Hello').append(' ').append('World');
console.log(sb.toString()); // 输出 "Hello World"
直接使用字符串拼接
对于少量字符串拼接,直接使用+=操作符足够高效。但在循环或大量拼接时,性能可能较差。
let result = '';
result += 'Hello';
result += ' ';
result += 'World';
console.log(result); // 输出 "Hello World"
使用模板字符串
ES6的模板字符串提供了一种简洁的拼接方式,适合已知内容的静态拼接。
const part1 = 'Hello';
const part2 = 'World';
const result = `${part1} ${part2}`;
console.log(result); // 输出 "Hello World"
性能比较
- 数组
join方法适合高频或大量拼接场景。 - 直接拼接适合简单或少量操作。
- 模板字符串适合静态内容或已知片段。
选择方法时需根据具体场景权衡可读性和性能。






