[Python-ideas] bool keyword: (was [Python-Dev] bool conversion wart?)

Ron Adam rrr at ronadam.com
Sat Mar 3 08:14:42 CET 2007


Josiah Carlson wrote:
> Ron Adam <rrr at ronadam.com> wrote:
>> So I have no problem if it's ruled out on the grounds that 'there is not 
>> sufficient need'
> 
> Ok.  YAGNI.  Seriously.  The performance advantage in real code, I
> guarantee, isn't measurable. 

It is measurable, but the total average gain would not be substantial only 
because of it being a relatively rare operation.


The most common use of bool() seems to be in returning a bool value.

    return bool(exp)



A few timeit tests...


The bool constructor:

$ python2.5 -m timeit -n 10000000 'bool(1)'
10000000 loops, best of 3: 0.465 usec per loop

$ python2.5 -m timeit -n 10000000 'bool("a")'
10000000 loops, best of 3: 0.479 usec per loop

$ python2.5 -m timeit -n 10000000 'bool([1])'
10000000 loops, best of 3: 0.697 usec per loop


A bool operator would have the same (or faster) speed as the 'not' operator:

$ python2.5 -m timeit -n 10000000 'not 1'
10000000 loops, best of 3: 0.165 usec per loop

$ python2.5 -m timeit -n 10000000 'not "a"'
10000000 loops, best of 3: 0.164 usec per loop

$ python2.5 -m timeit -n 10000000 'not [1]'
10000000 loops, best of 3: 0.369 usec per loop



The real gain is dependent on how and where it is used of course.  In most 
cases 'not not x' would still be much faster than bool(x).  Its nearly as 
fast as a single 'not' but really isn't the most readable way to do it.

$ python2.5 -m timeit -n 10000000 'not not 1'
10000000 loops, best of 3: 0.18 usec per loop

$ python2.5 -m timeit -n 10000000 'not not "a"'
10000000 loops, best of 3: 0.185 usec per loop

$ python2.5 -m timeit -n 10000000 'not not [1]'
10000000 loops, best of 3: 0.381 usec per loop



The following may be an indication of how much speed difference may still 
be gained in other related situations such as flow control or comparisons 
where bool values are used implicitly.

$ python2.5 -m timeit -n 10000000 'if "a": pass'
10000000 loops, best of 3: 0.0729 usec per loop

$ python2.5 -m timeit -n 10000000 'if not "a": pass'
10000000 loops, best of 3: 0.17 usec per loop

$ python2.5 -m timeit -n 10000000 'if bool("a"): pass'
10000000 loops, best of 3: 0.486 usec per loop


In the case of a bool operator, it's not a major issue because of how 
rarely it's actually used.

Cheers,
   Ron








More information about the Python-ideas mailing list