Given the following three functions
def v1(a):
c = 0
for a_ in a:
if a_ is not None:
c += 1
return c
def v2(a):
c = 0
for a_ in a:
if a_:
c += 1
return c
def v3(a):
c = 0
for a_ in a:
if bool(a_):
c += 1
return c
I get the following performance (I'm using python 3.6 on ubuntu 18.04)
values = [random.choice([1, None]) for _ in range(100000)]
%timeit v1(values)
3.35 ms ± 28 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit v2(values)
2.83 ms ± 36.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit v3(values)
12.3 ms ± 59.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
The similar performance between v1
and v2
makes sense, but why is v3
so much slower given that v2
is presumably implicitly calling bool(a_)
too?
Is it simply calling bool()
from python rather than from c (as I assume if
does) that's causing the difference in performance?