I made an interesting observation the other day. I experimented with various ways to get the "truth" of the object and the speed of each, and I noticed that not much faster than bool .
>>> bool([5, 6, 7]) True >>> bool([]) False >>> not not [5, 6, 7] True >>> not not [] False >>> import timeit >>> from numpy import mean >>> mean(timeit.repeat('bool(a)', 'a = [5, 6, 7]', repeat=10)) 0.19072036743164061 >>> mean(timeit.repeat('bool(a)', 'a = []', repeat=10)) 0.18562331199645996 >>> mean(timeit.repeat('not not a', 'a = [5, 6, 7]', repeat=10)) 0.072056698799133304 >>> mean(timeit.repeat('not not a', 'a = []', repeat=10)) 0.073475956916809082 >>> mean(timeit.repeat('not a', 'a = [5, 6, 7]', repeat=10)) 0.043941426277160647 >>> mean(timeit.repeat('not a', 'a = []', repeat=10)) 0.044287109375000001
We see that using the bool function is much slower than using the not operator, although in the end they do the same (return the logical state of the object). Now we have all been told that in Python, the overhead is large, but I did not expect this kind of inconsistency in this case for the following reasons:
bool() is a built-in function meaning that it is written in C, and I expected this to have fairly low overhead- In both cases, Python must evaluate the "likelihood" of the object inside (I would suggest that they use the same C routines to do this inside)
- In fact,
not should return the logical opposite of the “likelihood” object, so theoretically it does a bit more work (but maybe there are implementation details that get around this).
In my opinion, since both functions perform almost the same thing, all the extra time should come from service functions. If so, why can the operator avoid too much overhead compared to the function? If this is not overhead, why is bool() so slower than not ?
UPDATE: Minimum values are also shown here in addition to the average.
>>> min(timeit.repeat('bool(a)', 'a = [5, 6, 7]', repeat=10)) 0.18180489540100098 >>> min(timeit.repeat('bool(a)', 'a = []', repeat=10)) 0.1821761131286621 >>> min(timeit.repeat('not not a', 'a = [5, 6, 7]', repeat=10)) 0.0707249641418457 >>> min(timeit.repeat('not not a', 'a = []', repeat=10)) 0.07100605964660645 >>> min(timeit.repeat('not a', 'a = [5, 6, 7]', repeat=10)) 0.04264092445373535 >>> min(timeit.repeat('not a', 'a = []', repeat=10)) 0.04357004165649414