Performance is probably not the first thing that pops up in your mind when you think about Python. Nor is it required in a typical I/O intensive application, where most CPU cycles are spent waiting. But if a few small fixes can give your program those tiny performance boosts, that doesn’t hurt, right?

Here are three easy fixes which you can give your Python code that little extra speed that it deserves.

1. Using {} instead of dict to initialize a dictionary

When initializing a new dictionary, using {} is much more performant than calling the dict built-in.

$ python3 -m timeit "x = dict()"
2000000 loops, best of 5: 111 nsec per loop

$ python3 -m timeit "x = {}"
10000000 loops, best of 5: 30.7 nsec per loop

To see why, let’s look at the bytecode representation of both the statements.

>>> dis.dis("x = dict()")
  1           0 LOAD_NAME                0 (dict)
              2 CALL_FUNCTION            0
              4 STORE_NAME               1 (x)
              6 LOAD_CONST               0 (None)
              8 RETURN_VALUE
>>> dis.dis("x = {}")
  1           0 BUILD_MAP                0
              2 STORE_NAME               0 (x)
              4 LOAD_CONST               0 (None)
              6 RETURN_VALUE

dict is slower because it calls a function that essentially returns {}. Hence, any occurrences of dict() can be safely replaced with {}.

Take care, however, that you’re not using {} (or even dict(), since it returns {}) in variables that will be passed around to a lot of functions. In such cases, you may want to pass the dict callable, and then execute the callable only inside the function.

#optimizations #python #python code

Easy performance optimizations in Python
1.20 GEEK