[PATCH] cleanup: use x in (a, b) instead of x == a or x == b

Matt Mackall mpm at selenic.com
Thu Sep 23 16:05:48 CDT 2010


On Thu, 2010-09-23 at 19:02 +0200, Isaac Jurado wrote:
> Replying Matt Mackall:
> > 
> > optimal:
> > $ python -m timeit -s 'a, b, c = 0, 0, 2' -c 'if a == b or a == c: pass'
> > 10000000 loops, best of 3: 0.083 usec per loop
> > $ python -m timeit -s 'a, b, c = 0, 0, 2' -c 'if a == (b, c): pass'
> > 1000000 loops, best of 3: 0.28 usec per loop
> > 
> > pessimal:
> > $ python -m timeit -s 'a, b, c = 0, 1, 2' -c 'if a == b or a == c: pass'
> > 10000000 loops, best of 3: 0.134 usec per loop
> > $ python -m timeit -s 'a, b, c = 0, 1, 2' -c 'if a == (b, c): pass'
> > 1000000 loops, best of 3: 0.29 usec per loop
> 
> Just for the record.  I don't know if the "a == (b, c)" expression is
> intentional or a typo, but in both pessimal and optimal cases there is
> almost no time difference because a scalar is being compared with a
> tuple.
> 
> Changing it to "a in (b, c)", what the whole thread was all about, shows
> the difference between the two cases.

Yep, thinko on my part. Corrected examples, numbers:

optimal:
$ python -m timeit -s 'a, b, c = 0, 0, 2' -c 'if a == b or a == c: pass'
10000000 loops, best of 3: 0.083 usec per loop
$ python -m timeit -s 'a, b, c = 0, 0, 2' -c 'if a in (b, c):
pass'10000000 loops, best of 3: 0.193 usec per loop

pessimal:
$ python -m timeit -s 'a, b, c = 0, 1, 2' -c 'if a == b or a == c: pass'
10000000 loops, best of 3: 0.134 usec per loop
$ python -m timeit -s 'a, b, c = 0, 1, 2' -c 'if a in (b, c): pass'
1000000 loops, best of 3: 0.28 usec per loop

Both the thinko and the fixed version do a good job of highlighting the
hidden cost of tuples.

(That's py2.5 and 2.6 is similar. The gap has shrunk in py3.1 though:
one result gets substantially worse and the other gets substantially
better.)

-- 
Mathematics is the supreme nostalgia of our time.




More information about the Mercurial-devel mailing list