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);
每个搜索单词一次
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$newphrase = str_replace("fruits", "pizza", $phrase);
$newphrase = str_replace("vegetables", "beer", $phrase);
My question is if using array on str_replace is faster than doing it multiple times. My question goes for only two replaces.
With array
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables");
$yummy = array("pizza", "beer");
$newphrase = str_replace($healthy, $yummy, $phrase);
each search word once
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$newphrase = str_replace("fruits", "pizza", $phrase);
$newphrase = str_replace("vegetables", "beer", $phrase);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 PHP 文档 str_replace :
查看这些示例,PHP 正在为每个
$search
数组节点应用str_replace
,因此你的两个例子在性能方面是相同的但是,可以肯定的是,使用数组进行搜索和替换更具可读性和未来的专业性,因为您将来可以轻松地更改数组。From PHP Docs on str_replace :
Looking at those examples, PHP is applying the
str_replace
for each$search
array node so both of your examples are the same in terms of performance however sure using an array for search and replace is more readable and future-prof as you can easily alter the array in future.我不知道它是否更快,但我倾向于使用数组路由,因为它对我来说更易于维护和可读...
如果我不得不猜测,我会说多次调用 str_replace 会更慢,但我不确定str_replace 的内部结构。对于这样的东西,我倾向于考虑可读性/可维护性,因为优化的好处并不存在,因为根据替换的数量,你可能只会得到大约 0.0005 秒的差异。
如果你真的想找出时间差,那么如果不建立一个巨大的数据集,以便达到可以看到实际时间差与测试混淆中的异常的程度,那几乎是不可能的。
使用这样的东西......
将允许您计时请求。
I don't know if it's faster but I tend do go with the array route because it's more maintainable and readable to me...
If I had to guess I would say making multiple calls to str_replace would be slower but I'm not sure of the internals of str_replace. With stuff like this I've tended to go with readability/maintainability as the benefit to optimization is just not there as you might only get around 0.0005 seconds of difference depending on # of replacements.
If you really want to find out the time difference it's going to be close to impossible without building up a hugh dataset in order to get to the point where you can see an actual time difference vs anomalies from test confounds.
Using something like this ...
... will allow you to time a request.
尝试在每种不同的方法之前和之后使用它,您很快就会看到是否存在速度差异:
Try using this before and after each different method and you will soon see if there is a speed difference: