PHP 中哪个更快,是一个大的 switch 语句,还是每次都要进行数组初始化的数组键查找?
在 PHP 中,制作大型 switch 语句或设置数组并查找键哪个更快?
现在,在您回答之前,我很清楚,对于纯查找,数组速度更快。但是,这是假设仅创建一次数组,然后重复查找它。
但这不是我正在做的 - 每次运行代码都是新的,并且每次都会使用该数组一次。因此,每次都需要重新计算所有数组哈希值,我想知道执行此设置是否比简单地使用 switch
语句慢。
What's faster in PHP, making a large switch statement, or setting up an array and looking up the key?
Now before you answer, I am well aware that for pure lookups the array is faster. But, this is assuming creating the array just once, then looking it up repeatedly.
But that's not what I'm doing - each run through the code is new, and the array will be used just once each time. So all the array hashes need to be calculated fresh each time, and I'm wondering if doing that setup is slower than simply having a switch
statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我做了一些测试:
文件 array_gen.php
文件 switch_gen.php:
然后:
然后我将循环修改为:
创建 17576 个 3 个字母组合。
数组方法每次都会获胜,即使包含设置时间也是如此。但不是很多。所以我想我会忽略这个优化并选择更简单的方法。
I did some tests:
File array_gen.php
File switch_gen.php:
Then:
Then I modified the loop to:
To create 17576, 3 letter combinations.
The array method wins every time, even once you include setup time. But not by a lot. So I think I will ignore this optimization and go with whatever is easier.
它在某种程度上取决于数组大小,但对于大多数实际目的,您可以认为数组更快。原因很简单; switch 语句必须按顺序与 switch 语句中的每个条目进行比较,但数组方法只是采用散列并找到该条目。当开关中的条目太少以至于顺序比较比散列更快时,使用开关会更快,但数组方法会很快变得更加高效。用计算机科学术语来说,这是一个 O(n) 与 O(1) 的问题。
It sort of depends on the array size, but for most practical purposes, you can consider that the array is faster. The reason is simple; a switch statement must compare sequentially against each entry in the switch statement, but the array approach simply takes the hash and finds that entry. When you have so few entries in your switch that the sequential comparisons are faster than the hashing, it's faster to use a switch, but the array approach becomes more efficient quickly. In computer science terms, it's a question of O(n) vs. O(1).