Php 用数组替换str_是否更快?

Php 用数组替换str_是否更快?,php,performance,str-replace,Php,Performance,Str Replace,我的问题是,在str_replace上使用数组是否比多次使用要快。我的问题只涉及两个方面 带数组 $phrase = "You should eat fruits, vegetables, and fiber every day."; $healthy = array("fruits", "vegetables"); $yummy = array("pizza", "beer"); $newphrase = str_replace($healthy, $yummy, $phrase);

我的问题是,在str_replace上使用数组是否比多次使用要快。我的问题只涉及两个方面

带数组

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables");
$yummy   = array("pizza", "beer");

$newphrase = str_replace($healthy, $yummy, $phrase);
每个搜索词一次

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$newphrase = str_replace("fruits", "pizza", $phrase);

$newphrase = str_replace("vegetables", "beer", $phrase);

我不知道它是否更快,但我倾向于使用数组路径,因为它对我来说更易于维护和可读

$replace = array();
$replace['fruits']     = 'pizza';
$replace['vegetables'] = 'beer';

$new_str = str_replace(array_keys($replace), array_values($replace), $old_str);
如果我不得不猜测的话,我会说多次调用str_replace会更慢,但我不确定str_replace的内部结构。对于这样的东西,我倾向于使用可读性/可维护性,因为优化的好处并不存在,因为根据替换的数量,您可能只能获得大约0.0005秒的差异

如果你真的想找出时差,那么如果不建立hugh数据集,就几乎不可能找到,这样你就可以从测试混淆中看到实际时差与异常

用这样的东西

$start = microtime(true);
// Your Code To Benchmark
echo (microtime(true) - $start) . "Seconds"
。。。将允许您对请求计时。

从开始:


看看这些例子,PHP正在为每个
$search
数组节点应用
str_replace
,因此这两个示例在性能上是相同的,但是确保使用数组进行搜索和替换更具可读性和未来性,因为您可以在将来很容易地更改数组。

尝试在每个不同的方法之前和之后使用此方法,您可以将很快查看是否存在速度差:

echo microtime()

可能但两者之间的差异可能非常小。(在您的平台上测量具体答案)最快的解决方案是从以下代码开始:
$phrase=“您应该每天吃比萨饼、啤酒和纤维。”@PeterAjtai Hm。。是的,为什么我没有想到这个?是的,如果你的数组不好,你可以在索引上给它一个小耳光,让它成为一个好孩子…;-)秘密提示:
strr($old\u str,$replace)
:)
echo microtime()