I’m coding a classical cipher by substitution in C++, using all the printable characters in ASCII, and I’m wondering which is faster? A search in an array (edit: a non associative one, just something like letters[] = {'a', 'b', ...); (linear or binary) or a switch statement? The compiler can optimize the switch, doesn’t it?. Maybe the difference is the memory usage? My choice is the switch, although the code is bigger, but maybe I’m missing something.
(Perhaps this question seems subjective, but I think would be objective reasons to choose one or another way. And sorry for my English).
There’s certainly a chance that a sufficiently smart compiler could optimize the switch to be a lookup, which would be faster than a binary search. But you could do that optimization yourself and get short code: