Why is truth() faster than bool()? Part I

At TellApart, we use Python to code our real-time bidding server. Real-time bidding means we have to respond in a few milliseconds to requests from ad exchanges, or else we’re, well, out of business. So it’s critical that we know how to use all of our tools effectively.

There are faster languages than Python, but if you’re writing Python you can still speed things up without making anything less readable. Even where performance differences are small it pays to know what you’re doing. The knowledge may come in handy someday when you discover that an apparently simple piece of code has a disproportionate impact on execution time, perhaps only because it’s in a block that gets executed zillions of times.

With that introduction, here’s a survey of some tips we’ve assembled to write performant Python code on a line-by-line basis.

Today we’ll learn:

  1. How to use timeit
  2. Why you should prefer tuples instead of lists
  3. Where and why you should use generator expressions instead of list expressions
  4. The right way to instantiate a set()
  5. Why not to use dict.keys()

Read More