Search code examples
pythonpython-2.7optimizationbytecode

Python optimization through bytecode


When it comes to optimization of Python code (or any code), it often ends up coming down to profiling to optimize bottlenecks or slow functions. However, when optimizing these areas of code, are there any use cases for using pure Python bytecode inline? I know you can do this through the use of the compile built-in function and compiler module.


Solution

  • ... are there any use cases for using pure Python bytecode inline?

    Yes. Sometimes you can handroll a little faster code than Python normally generates on its own.

    Also, you can gain access to the loop induction variables for list comprehensions.

    Here are some links to get you started: https://www.google.com/search?q=python+bytecode+hacks

    If you would like to make the bytecode manipulations programmatically, here is an optimization recipe that shows how to go about it: Decorator for BindingConstants at compile time

    That said, if you care about speed, the simplest speed-up is often to run pypy instead of cpython if your application allows it.