In PHP what's faster, 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, 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.
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).
Did some tests:
array_gen.php:
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.