Skip to content Skip to sidebar Skip to footer

Why Is Python's 'all' Function So Slow?

I have wrote some very simple tests (I know, they are not 'conclusive', but they make me curious). I ran with optimization and all that jazz. from time import time alist = [ 2, 4

Solution 1:

all() definitely does exit early, I think the behavior difference is just the result of the overhead required to create the generator.

Here is some proof that all() does exit early:

In [8]: alist = [3] + [0] *2**20    # alist bigger, with an early odd

In [10]: %timeit all_even(alist)
1000000 loops, best of3: 309 ns per loop

In [11]: %timeit all_even_bad(alist)
10 loops, best of3: 133 ms per loop

In [12]: %timeit all(val &1==0for val in alist)
1000000 loops, best of3: 891 ns per loop

Note that even though all() is slower than all_even() here, it is still significantly faster than the version of the function that doesn't exit early.

Solution 2:

You have no elements that fail the test, therefore there is no way for it to short circuit.

Solution 3:

Since all of the numbers in your list are in fact even, it could not logically bail out early? The overhead of your all() call might come from the construction of a generator object.

Post a Comment for "Why Is Python's 'all' Function So Slow?"