str_replace 为 strpos?
带 strpos 检查的 str_replace 函数可以避免额外的工作吗?
方法 1
...
if (strpos($text, $tofind) !== FALSE)
$text = str_replace($tofind, $newreplace, $text);
...
方法 2
...
$text = str_replace($tofind, $newreplace, $text);
...
问题:这两种方法有效,但是......我想知道 strpos 检查(或其他)是好方法还是坏方法,无用(以及优化)反模式)。
The str_replace function with a strpos checking can avoid extra work?
METHOD 1
...
if (strpos($text, $tofind) !== FALSE)
$text = str_replace($tofind, $newreplace, $text);
...
METHOD 2
...
$text = str_replace($tofind, $newreplace, $text);
...
Question: This two methods works but... I want know if strpos-checking (or other) is good way or a bad, useless (and optimization antipattern).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可能会保存一些
str_replace()
调用,但您总是会得到额外的strpos()
调用和!== false
比较。然而,我认为,只要这段代码不会运行大约 100000 次(或类似的次数),它就不会产生任何可衡量的影响。因此,只要您不需要知道,如果需要进行替换,您就应该避免这种“优化”,以使事情更加简单和可读。
You may save some
str_replace()
calls, but you get always additionalstrpos()
-calls and!== false
comparisons. However, I don't think, that it will make any measureable impact, as long as this code will not run around 100000 times (or such).Thus as long as you don't need to know, if there are replacements to made, you should avoid this "optimization" to keep things more simple and readable.
您始终可以自己计时:
添加
strpos
每次都会变慢,但不会慢很多。一个好的经验法则是不要猜测你的瓶颈在哪里。功能代码和良好、简洁的设计。之后,您可以在性能测试需要时分析。
You can always time things yourself:
Adding
strpos
is slower every time, but not by much.A good rule of thumb is don't guess where your bottlenecks will be. Code for functionality and good, clean design. After that, you can profile when performance tests warrant it.
没有strpos的方法更好。
我们假设 strpos 和 str_replace 具有相同的最坏情况运行时间,因为它们都必须迭代整个文本。
通过使用两者,在最坏的情况下,运行时间比单独使用 str_replace 增加了一倍。
The method without strpos is better.
Let's assume that both the strpos and the str_replace have the same worst case running time, because they both have to iterate through the whole text.
By using both, you have in the worst case, double the running time than just using str_replace alone.
我刚刚测试了 3 种方法来替换我的配置文件中的常量:
一些测量:
在我的所有测试中,没有检查方法使用的时间至少是两倍!
strstr
和strpos
方法之间似乎没有显着差异。I've just tested 3 ways to replace constants in my config file :
Some measurements :
No check method used a least double of the time in all my tests !
It seems to not have significant difference between
strstr
andstrpos
methods.另一个基准测试结果如下:使用 strpos: http://3v4l.org/pb4hY#v533 不使用 strpos: < a href="http://3v4l.org/v35gT" rel="nofollow">http://3v4l.org/v35gT
Another benchmark results here: with strpos: http://3v4l.org/pb4hY#v533 without strpos: http://3v4l.org/v35gT