Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
The community reviewed whether to reopen this question 6 months ago and left it closed:
Original close reason(s) were not resolved
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
来自 PHP 在线手册:
From the PHP online manual:
这里是我得到的问题的一些其他答案(+基准),它几乎相同(我在提问时没有意识到你的答案)。
与此同时,我还做了自己的基准测试,对每个相关函数(
strstr()
、strpos()
、stristr)运行了 1000000 次。 ()
和stripos()
)。代码如下:
这是第一个输出,它表明
strpos()
是获胜者:下一个输出与第一个输出类似 (
strpos( )
又是获胜者):下面是另一个,更有趣,因为在这种情况下,
strstr()
是获胜者:这意味着它确实可以依赖于“环境情况”,有时很难影响,并且可以像这样更改“微优化任务”的结果,以防您只是检查字符串是否存在于另一个字符串中。
但我认为在大多数情况下,与
strstr()
相比,strpos()
是赢家。我希望这个测试对某人有用。
Here are some other answers (+benchmarks) I got to my question, which is almost the same (I didn't realize yours when asking).
In the meantime I also made my own benchmark test, which I ran 1000000 times for each relevant functions (
strstr()
,strpos()
,stristr()
andstripos()
).Here's the code:
And here is the first output, which shows that
strpos()
is the winner:The next one is similar to the first output (
strpos()
is the winner again):Below is another one, which is more interesting, because in this case,
strstr()
is the winner:This means it can really depend on "environmental circumstances", which are sometimes hard to influence, and can change the result of "micro optimization tasks" like this, in case you are just checking whether a string exists in another one or not.
BUT I think in most cases,
strpos()
is the winner in comparison tostrstr()
.I hope this test was useful for someone.
许多开发人员使用
strpos
来实现微优化目的。使用
strstr
也仅在结果字符串在布尔上下文中无法解释为 false 时才有效。被事件所克服:PHP8 引入了
str_contains
,“适合这项工作的工具”(带有适用于旧设置的垫片)。这正是每个人都梦寐以求的,但没有解释器级别的比较和语法开销。Many developers use
strpos
for micro optimization purposes.Using
strstr
also only works if the resulting string cannot be interpreted as false in boolean context.Overcome by events: PHP8 introduced
str_contains
, the "right tool for the job" (with shims available for older setups). Which does exactly what everyone has been glamoring for, but without the interpreter-level comparison and syntactic overhead.strpos()
检测大海捞针中特定针所在的位置。strstr()
测试针是否位于大海捞针的任何位置。因此,strpos() 速度更快,内存消耗更少。
使用
strstr()
的原因:如果您的针位于字符串的开头,则strpos()
返回0
(因此您必须检查它与=== false
)strpos()
detects where in the haystack a particular needle lies.strstr()
tests whether the needle is anywhere in the haystack.Therefore
strpos()
is faster and less memory consuming.A reason for
strstr()
: if your needle is at the beginning of a string,strpos()
returns0
(so you have to check it with=== false
)