Oli*_* A. 14 php arrays string performance
在我当前的项目中,我将一个字符串组合成许多小字符串(直接输出不是一个选项).进行许多字符串连接会更有效吗?或者我应该将部件添加到阵列并将其内爆?
Sta*_*asM 15
首先是旁注 - 在实际的生产应用程序中任何一个都无关紧要,因为时间差异是肤浅的,应用程序的优化应该在其他地方完成(处理网络,数据库,文件系统等).话虽如此,出于好奇心的缘故:
implode
可能是更有效的连接,但只有你已经拥有数组.如果不这样做,它可能会变慢,因为所有增益都会被创建数组并分配其元素所需的时间所抵消.所以保持简单:)
Bra*_*tie 10
<?php
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
define('ITERATIONS', 10000);
header('Content-Type: text/plain');
printf("Starting benchmark, over %d iterations:\r\n\r\n", ITERATIONS);
print("Imploding...");
$start = microtime_float();
$list = Array();
for ($_ = 0; $_ < ITERATIONS; $_++)
$list[] = 'a';
$result = implode('',$list);
$end = microtime_float() - $start;
printf("%0.3f seconds\r\n", $end);
unset($list,$result);
print("Concatenating...");
$start = microtime_float();
$result = '';
for ($_ = 0; $_ < ITERATIONS; $_++)
$result .= 'a';
$end = microtime_float() - $start;
printf("%0.3f seconds\r\n", $end);
?>
Run Code Online (Sandbox Code Playgroud)
导致内爆的时间延长了99%.例如
Starting benchmark, over 10000 iterations:
Imploding...0.007 seconds
Concatenating...0.003 seconds
Run Code Online (Sandbox Code Playgroud)
与网络流量,数据库,文件,图形等相比,优化很少.但是,这里是来自sitepoint的主题参考.
http://www.sitepoint.com/high-performance-string-concatenation-in-php/
哪个最快?
好消息是PHP5很快.我测试了5.3版本,你比内存性能问题更有可能耗尽内存.但是,数组内爆方法通常需要标准连接运算符的两倍.连接字符串或构建数组需要相当的时间段,但内爆函数会使工作量增加一倍.
不出所料,PHP针对字符串处理进行了优化,在大多数情况下,点运算符将是最快的连接方法.