3 回答
TA贡献1803条经验 获得超6个赞
不,在PHP中没有stringbuilder类的类型,因为字符串是可变的。
话虽如此,根据您在做什么,有不同的方式来构建字符串。
例如,echo将接受逗号分隔的标记以进行输出。
// This...
echo 'one', 'two';
// Is the same as this
echo 'one';
echo 'two';
这意味着您无需实际使用连接就可以输出复杂的字符串,这会比较慢
// This...
echo 'one', 'two';
// Is faster than this...
echo 'one' . 'two';
如果需要在变量中捕获此输出,则可以使用输出缓冲功能来完成。
另外,PHP的数组性能非常好。如果要执行逗号分隔的值列表之类的操作,请使用implode()
$values = array( 'one', 'two', 'three' );
$valueList = implode( ', ', $values );
最后,请确保您熟悉PHP的字符串类型,它的不同定界符以及每个定界符的含义。
TA贡献2019条经验 获得超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();
结果:
10000次迭代:
1)PHP,普通串联:〜6ms
2)PHP,使用StringBuilder:
〜5 ms 3)C#,普通串联:〜520ms
4)C#,使用StringBuilder:〜1ms
100000次迭代:
1)PHP,普通串联:〜63ms
2)PHP,使用StringBuilder:〜555ms
3)C#,普通串联:〜91000ms // !!!
4)C#,使用StringBuilder:〜17ms
- 3 回答
- 0 关注
- 413 浏览
添加回答
举报