使用数组的str_replace是否更快?

5
我的问题是,在使用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);

6
可能是这样,但差异可能微不足道。(针对具体答案,请在您的平台上进行测量。) - Billy ONeal
4
好的,我会尽力为您翻译。以下是您提供的链接中的内容:Premature optimization is the root of all evil (or at least most of it) in programming.过早优化是编程中所有邪恶的根源(或至少是大多数邪恶的根源)。We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.我们应该忘记小的效率问题,大约有97%的时间:过早优化是所有邪恶的根源。Yet we should not pass up our opportunities in that critical 3%.然而,在关键的3%机会出现时,我们不应该放弃它们。A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified.一名好的程序员不会被这种理论所蒙蔽,他将明智地仔细查看关键代码;但是只有在确定了这些代码之后才能这样做。-- DonaldKnuth——唐纳德·克努特 - Amber
4
最快的解决方案就是从代码开始:$phrase = "每天你应该吃比萨、啤酒和纤维。"; - Peter Ajtai
1
@PeterAjtai 嗯...对啊,为什么我没想到呢? - EnexoOnoma
3个回答

1

来自PHP文档关于str_replace

// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);

// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit   = array('apple', 'pear');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);
echo $output;

看这些例子,PHP对每个$search数组节点应用了str_replace,因此在性能方面,您的两个示例是相同的,但是使用搜索和替换数组更易读且更具未来性,因为您可以轻松地在将来更改数组。


1
是的,如果你的数组有问题,你可以在索引上轻轻拍一下,让它成为一个好孩子...;-) - user166390

0

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

$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秒的差异,具体取决于替换的数量。

如果你真的想找出时间差异,除非建立一个庞大的数据集,否则几乎不可能达到实际时间差异与测试混淆的异常之间的平衡点。

使用类似这样的东西...

$start = microtime(true);
// Your Code To Benchmark
echo (microtime(true) - $start) . "Seconds"

...将允许您计时请求。


秘密提示:strtr($old_str, $replace) :) - NikiC

-1

在每个不同的方法之前和之后尝试使用这个,你很快就会看到是否有速度差异:

echo microtime()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接