php 字符串拼接 性能,PHP:字符串concat和缓冲内容之间的性能差异

这是您的基准:

$test_1_start = microtime();

$str = '';

for ( $x = 0; $x <= 10000; $x++ ) {

$str .= 'I am string ' . $x . "\n";

}

$test_1_end = microtime();

unset($str);

echo 'String concatenation: ' . ( $test_1_end - $test_1_start ) . ' seconds';

$test_2_start = microtime();

ob_start();

for ( $x = 0; $x <= 10000; $x++ ) {

echo 'I am string ', $x, "\n";

}

$str = ob_get_contents();

ob_end_clean();

$test_2_end = microtime();

echo "\nOutput buffering: " . ( $test_2_end - $test_2_start ) . ' seconds';

?>我的结果:

$ php -v

PHP 5.3.4 (cli) (built: Dec 15 2010 12:15:07)

Copyright (c) 1997-2010 The PHP Group

Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

$ php test.php

String concatenation: 0.003932 seconds

Output buffering: 0.002841 seconds%

$ php test.php

String concatenation: 0.004179 seconds

Output buffering: 0.002796 seconds%

$ php test.php

String concatenation: 0.006768 seconds

Output buffering: 0.002849 seconds%

$ php test.php

String concatenation: 0.004925 seconds

Output buffering: 0.002764 seconds%

$ php test.php

String concatenation: 0.004066 seconds

Output buffering: 0.002792 seconds%

$ php test.php

String concatenation: 0.004049 seconds

Output buffering: 0.002837 seconds%看起来输出缓冲+ echo始终更快,至少在我的机器上的CLI /中。

然而,Brendan Long在他的评论中提出了一个很好的观点 - 这里有一个小的性能差异,选择一个或另一个并不是一个问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值