What's faster in PHP, a big switch statement, or an array key lookup where the array initialisation is paid every time?

前端 未结 2 810
半阙折子戏
半阙折子戏 2020-12-14 16:54

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 t

2条回答
  •  无人及你
    2020-12-14 17:12

    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).

提交回复
热议问题