使用'preg_replace'和带有多个索引的数组时会出现性能损失或其他负面因素吗?

时间:2011-06-20 05:47:48

标签: php arrays performance preg-replace

使用'preg_replace'和带有多个索引的数组时会出现性能损失或其他负面因素吗?

$string = 'The quick brown fox jumped over the lazy dog.';

$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
...
$patterns[100] = '/fox/';

$replacements[0] = 'bear';
$replacements[1] = 'black';
...
$replacements[100] = 'slow';

echo preg_replace($patterns, $replacements, $string);

2 个答案:

答案 0 :(得分:3)

好吧,让我们看看

/** Get current time with microseconds */
function gettime() {
  list($ms, $s) = explode(' ', microtime());
  return (float)$s + (float)$ms;
}

define('PAT_COUNT', 20000);

$patterns = array();
$replacements = array();
// The string will be the same for both tests
$string = '';
for ($i = 0; $i < PAT_COUNT; $i++) {
  $string .= "$i ";
  $patterns[] = "/$i /";
  $replacements[] = ":$i:";
}

$start = gettime();
$result1 = preg_replace($patterns, $replacements, $string);
echo "preg_replace with arrays: ".(gettime() - $start)."\n";

$start = gettime();
$result2 = $string;
for($i = 0; $i < PAT_COUNT; $i++) {
  $result2 = preg_replace("/$i /", ":$i:", $result2);
}
echo "preg_replace inside of a loop: ".(gettime() - $start)."\n";

输出

preg_replace with arrays: 19.568552017212
preg_replace inside of a loop: 20.119801044464

实际上它甚至更快一点,但不是很明显。也许是因为它在实现中有一些优化的循环。

但谁知道,也许您的数据结果会有所不同。尝试使用您的数据样本制作这样的基准。

答案 1 :(得分:0)

对于这种简单的查找,我建议使用str_replace而不是正则表达式。当你想比较循环时,最好展开循环或使用Duff设备。