Optimizing python code
1 | def is_letter(character): |
I noticed this function would loop from a-Z so we should speed that up using a set!
First is it slow?
1 | In [5]: %timeit is_letter(';') |
I guess not it took 1 second to do ~10M on its worst case input
But we should be able to speed it up using a set (one hash lookup rather than looking at all 52 things)
1 | def is_letter(character): |
1 | In [7]: %timeit is_letter(';') |
Okay so thats ~20x slower because it constructs a set on every loop.
lets fix that
1 | letters = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') |
1 | In [9]: %timeit is_letter(';') |
So thats roughly 10% faster!
It can be easy to trip up trying to optimize code.
Its also easy to achieve underwhelming results.
Writing hard to detect bugs or slowing things down are a possibility, be sure to profile things on similar inputs to what you expect and test your code!
note: you can just usecharacter.isalpha()
it has similar performance