Josh Rosenberg added the comment:

It is a little funny though. I expect a more common test like:

if a < b < c: pass

to be unconditionally faster than the logically equivalent:

if a < b and b < c: pass

The only difference between the two should be that b is loaded only once, which 
should make the chained comparison either equivalent or faster. But thanks to 
the additional stack manipulations needed, in microbenchmarks, this isn't the 
case. I was just testing a couple simple cases in ipython (3.5, Linux, x64), 
and the chained comparison is actually slower when short-circuiting is involved:

%%timeit -r5 a, b, c = range(3, 0, -1)
if a < b < c: pass
10000000 loops, best of 5: 33.7 ns per loop

%%timeit -r5 a, b, c = range(3, 0, -1)
if a < b and b < c: pass
10000000 loops, best of 5: 25 ns per loop

or even without short-circuiting, but with the final test failing, chained 
loses (by a smaller margin):

%%timeit -r5 a, b, c = 0, 1, 0
if a < b < c: pass
10000000 loops, best of 5: 42.5 ns per loop

%%timeit -r5 a, b, c = 0, 1, 0
if a < b and b < c: pass
10000000 loops, best of 5: 39.3 ns per loop

The same pattern holds if a and c are replaced with constants, e.g. if 0 < b < 
2: (so only b is loaded by name). Yes, it's a small difference; when a, b, c 
are initialized from range(3), so all tests succeed, chained comparisons win, 
44.9 ns to 54.5 ns. But it seems kind of odd that the simplest case of a 
chained comparison is actually a pessimization in two of the three cases.

Not saying it's worth changing (I doubt chained comparisons occur in code 
enough to justify the tiny savings a dedicated op code could provide), but it's 
not something I'd reject out of hand.

----------
nosy: +josh.r

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue27236>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to