Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用'时存在性能影响或其他负面因素;preg#u替换';和具有多个索引的数组?_Php_Arrays_Performance_Preg Replace - Fatal编程技术网

Php 使用'时存在性能影响或其他负面因素;preg#u替换';和具有多个索引的数组?

Php 使用'时存在性能影响或其他负面因素;preg#u替换';和具有多个索引的数组?,php,arrays,performance,preg-replace,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'; ... $re

当使用“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);
好吧,让我看看

/** 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";
事实上它甚至快了一点,但不值得注意。可能是因为它的实现中有某种优化的循环


但谁知道呢,也许有了你的数据,结果会有所不同。试着用你的数据样本做一个这样的基准测试。

为了便于查找,我建议str\u replace而不是regulare expression。当您想要比较一个循环时,最好展开一个循环或使用一个Duff设备

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