I want to find the fastest way to do the job of switch
in C. I'm writing some Python code to replace C code, and it's all working fine except for a bottleneck. This code is used in a tight loop, so it really is quite crucial that I get the best performance.
Optimsation Attempt 1: First attempt, as per previous questions such as this suggest using hash tables for lookups. This ended up being incredibly slow.
Optimsation Attempt 2
Another optimisation I have made is to create a run of if ... return
statements which gives me a 13% speed boost. It's still disappointingly slow.
Optimsation Attempt 3
I created an array.array
of all possible input values, and did an index lookup. This results in an over-all speed up of 43%, which is respectable.
I'm running over an array.array
using map
and passing a transform function to it. This function is doing the lookup. My switch is working on short integers (it's a typed array). If this were GCC C, the compiler would create a jump table. It's frustrating to know that Python is either hashing my value to lookup a table entry or in the case of if, performing lots of comparisons. I know from profiling it that the slow functions are precisely the ones that are doing the look-up.
What is the absolute fastest way of mapping one integer to another, mapped over an array.array
if relevant. Anything faster than the above?
EDIT
Although it makes me look like an idiot for only just realising, I will say it anwyay! Remember that running your code in a profiler slows your code down a lot. In my case, 19 times slower. Suddenly my bottleneck isn't so bad! Thanks very much everyone for all your answers. The question is still valid. I'll leave the question open for a bit because there may be some interesting answers.
With profiler, for my test set of data:
real 0m37.309s
user 0m33.263s
sys 0m4.002s
without:
real 0m2.595s
user 0m2.526s
sys 0m0.028s