3 回答

TA貢獻(xiàn)1803條經(jīng)驗 獲得超6個贊
不,在PHP中沒有stringbuilder類的類型,因為字符串是可變的。
話雖如此,根據(jù)您在做什么,有不同的方式來構(gòu)建字符串。
例如,echo將接受逗號分隔的標(biāo)記以進(jìn)行輸出。
// This...
echo 'one', 'two';
// Is the same as this
echo 'one';
echo 'two';
這意味著您無需實際使用連接就可以輸出復(fù)雜的字符串,這會比較慢
// This...
echo 'one', 'two';
// Is faster than this...
echo 'one' . 'two';
如果需要在變量中捕獲此輸出,則可以使用輸出緩沖功能來完成。
另外,PHP的數(shù)組性能非常好。如果要執(zhí)行逗號分隔的值列表之類的操作,請使用implode()
$values = array( 'one', 'two', 'three' );
$valueList = implode( ', ', $values );
最后,請確保您熟悉PHP的字符串類型,它的不同定界符以及每個定界符的含義。

TA貢獻(xiàn)2019條經(jīng)驗 獲得超9個贊
PHP中不需要StringBuilder模擬。
我做了幾個簡單的測試:
在PHP中:
$iterations = 10000;
$stringToAppend = 'TESTSTR';
$timer = new Timer(); // based on microtime()
$s = '';
for($i = 0; $i < $iterations; $i++)
{
$s .= ($i . $stringToAppend);
}
$timer->VarDumpCurrentTimerValue();
$timer->Restart();
// Used purlogic's implementation.
// I tried other implementations, but they are not faster
$sb = new StringBuilder();
for($i = 0; $i < $iterations; $i++)
{
$sb->append($i);
$sb->append($stringToAppend);
}
$ss = $sb->toString();
$timer->VarDumpCurrentTimerValue();
在C#(.NET 4.0)中:
const int iterations = 10000;
const string stringToAppend = "TESTSTR";
string s = "";
var timer = new Timer(); // based on StopWatch
for(int i = 0; i < iterations; i++)
{
s += (i + stringToAppend);
}
timer.ShowCurrentTimerValue();
timer.Restart();
var sb = new StringBuilder();
for(int i = 0; i < iterations; i++)
{
sb.Append(i);
sb.Append(stringToAppend);
}
string ss = sb.ToString();
timer.ShowCurrentTimerValue();
結(jié)果:
10000次迭代:
1)PHP,普通串聯(lián):?6ms
2)PHP,使用StringBuilder:
?5 ms 3)C#,普通串聯(lián):?520ms
4)C#,使用StringBuilder:?1ms
100000次迭代:
1)PHP,普通串聯(lián):?63ms
2)PHP,使用StringBuilder:?555ms
3)C#,普通串聯(lián):?91000ms // !!!
4)C#,使用StringBuilder:?17ms
- 3 回答
- 0 關(guān)注
- 429 瀏覽
添加回答
舉報