PHP 中字符串拼接頻繁產生臨時副本,大量拼接時性能下降明顯。ASP.NET StringBuilder 通過內部數組緩衝區解決此問題。本文提供一個輕量級 PHP 實現,API 風格貼近原版。
class StringBuilder {
const LINE = "<br/>";
protected $buffer = array();
public function __construct($str = null) {
if ($str !== null) $this->buffer[] = $str;
}
public function Append($str) {
$this->buffer[] = $str;
return $this; // 支持鏈式調用
}
public function AppendLine($str) {
$this->buffer[] = $str . self::LINE;
return $this;
}
public function AppendFormat($format, ...$args) {
$this->buffer[] = sprintf($format, ...$args);
return $this;
}
public function ToString() {
return implode('', $this->buffer);
}
public function Clear() {
$this->buffer = array();
return $this;
}
public function __destruct() {
unset($this->buffer);
}
}
$sb = new StringBuilder();
$sb->Append('用戶: ')
->AppendFormat('%s (%s)', '張三', 'zhangsan@example.com')
->AppendLine('')
->Append('權限: ')
->AppendLine('管理員')
->AppendLine('編輯')
->AppendLine('查看');
echo $sb->ToString();
/* 輸出:
用戶: 張三 (zhangsan@example.com)<br/>
權限: 管理員<br/>
編輯<br/>
查看<br/>
*/
$n = 10000;
$str = '';
// 1. 直接拼接
$t = microtime(true);
for ($i=0; $i<$n; $i++) $str .= 'x';
echo "直接拼接: " . (microtime(true)-$t) . "s\n";
// 2. 數組收集 + implode
$t = microtime(true);
$arr = [];
for ($i=0; $i<$n; $i++) $arr[] = 'x';
$str = implode('', $arr);
echo "數組+implode: " . (microtime(true)-$t) . "s\n";
// 3. StringBuilder
$t = microtime(true);
$sb = new StringBuilder();
for ($i=0; $i<$n; $i++) $sb->Append('x');
$str = $sb->ToString();
echo "StringBuilder: " . (microtime(true)-$t) . "s\n";
/* 典型輸出 (PHP 8.1):
直接拼接: 0.0042s
數組+implode: 0.0018s
StringBuilder: 0.0021s
*/
結論:現代 PHP (7+) 對字符串拼接已優化極好,StringBuilder 優勢不明顯。但在超大字符串(>10MB)、頻繁插入中間、需鏈式 API 可讀性 時仍有價值。
Insert($index, $str)、Remove($start, $len)、Replace($old, $new) 等編輯操作Capacity 屬性預分配數組大小(array_pad)Countable、ArrayAccess 接口增強互操作性