5 ms·
Why do you suspect 1 <= len(vals) <= 5 would do something inefficient under the hood? You can actually get a very good idea for what Python is doing under the
by simonw 11y ago
Why do you suspect 1 <= len(vals) <= 5 would do something inefficient under the hood?
You can actually get a very good idea for what Python is doing under the hood using the dis module:
dis.dis(lambda: 1 <= len(vals) <= 5)
1 0 LOAD_CONST 1 (1)
3 LOAD_GLOBAL 0 (len)
6 LOAD_GLOBAL 1 (vals)
9 CALL_FUNCTION 1
12 DUP_TOP
13 ROT_THREE
14 COMPARE_OP 1 (<=)
17 JUMP_IF_FALSE_OR_POP 27
20 LOAD_CONST 2 (5)
23 COMPARE_OP 1 (<=)
26 RETURN_VALUE
>> 27 ROT_TWO
28 POP_TOP
29 RETURN_VALUE
Compare to:
dis.dis(lambda: len(vals) in range(1, 5))
1 0 LOAD_GLOBAL 0 (len)
3 LOAD_GLOBAL 1 (vals)
6 CALL_FUNCTION 1
9 LOAD_GLOBAL 2 (range)
12 LOAD_CONST 1 (1)
15 LOAD_CONST 2 (5)
18 CALL_FUNCTION 2
21 COMPARE_OP 6 (in)
24 RETURN_VALUE
- codys 11y agoEh? That dis output doesn't really tell us which is more efficient. To know that, you'd need to know how `COMPARE_OP` works for each of it's arguments, which is what @Negative1 believes will be not-as-efficient (along with range creation). This output doesn't really provide any clarification.
- lifthrasiir 11y agoThe bytecode count is, while significant in slower CPython interpreters, not directly an indicator of performance. `LOAD_GLOBAL` and `CALL_FUNCTION` are comparatively expensive opcodes to run.
- daveguy 11y agoIt may be a shorter number of bytecodes, but that does not mean it has better performance. You have two function calls in the range version and only one in the non-range version. You are just hiding some of that code in a dynamic function call. Also, your compare_op consists of two <= in the non-range version and an "in" compare_op for the range version (which probably hides the element by element comparison or hash/bloom if it is O(1). Fewer lines of code does not mean more efficient. Regardless of whether it is source code or bytecode.
- maxerickson 11y agoThere's no argument made in the comment you replied to. Certainly not a strident one in favor of range. It appears to me they went ahead and posted the bytecode for both because they had spun up an interpreter to get the bytecode for one.
- squeaky-clean 11y agoThat doesn't tell you about the speed of the code though. $> python -m timeit "1 <= 4 <= 5" 10000000 loops, best of 3: 0.0877 usec per loop $> python -m timeit "4 in range(1,5)" 1000000 loops, best of 3: 0.413 usec per loop $> python -m timeit "4 in (1,2,3,4,5)" 10000000 loops, best of 3: 0.0776 usec per loop Tested in python 3.5.0, Even with the improvements to the range function, the comparison is almost 5x faster.