This post compares different kinds of comparison operators in python with a microbenchmark.
Yesterday our team for the course Problem Solving and Engineering Design came across a peculiar statement in a piece of code. We were trying to optimize this code because it was a serious bottleneck in our program. The function which included the statement looked like so
We were wondering why
value & 0x01 and
0x01 were used instead of just simply
value is True. We
reasoned that if they used it in this way instead of the other (in this case)
equal, more readable way, it has to be faster.
We can divide the hypothesis in two parts:
&is faster than using
0x01is faster when comparing than using
I created a microbenchmark with the following script using the
The output of the microbenchmark above is:
Executing this script on different machines gives similar results.
When representing a
True value in hexadecimal format
0x01 the bitwise equals operation
1 & 0x01 is the
fastest. Both the normal equals comparison
1 is 0x01 and the
equals sign comparison
1 == 0x01 are about the same execution time
and are slower than the bitwise operation.
When using a normal representation for a
the normal equals comparison
1 is True is the fastest. The bitwise
1 & True is considerably slower than the normal
equals comparison. The slowest execution time is noted for the equals sign
1 == True.
All execution times for the equals comparison using the hexadecimal representation are faster than the execution times for the equals comparison using the normal representation.
We can conclude that by using the bitwise equals comparison and the
hexadecimal representation for
True results in the fastest
execution time. So both hypothesises are true. Using
1 & 0x01
can be twice as fast as the 'standard' equals comparison
Instead of using the hexadecimal representation
0x01, we can also simply use the decimal