3 ms·
> reversed(sorted(my_list)) I thought sorted(my_list, reverse=True) would be slightly faster, but it seems not (by a tiny amount). Weird. > "while True" shoul
by shazow 15y ago
> reversed(sorted(my_list))
I thought sorted(my_list, reverse=True) would be slightly faster, but it seems not (by a tiny amount). Weird.
> "while True" should be used in-place of "while 1". Reads better.
If you disassemble these statements, you'll see that "while 1" creates fewer instructions:
def foo():
while True:
pass
def bar():
while 1:
pass
import dis
dis.dis(foo)
# 0 SETUP_LOOP 10 (to 13)
# >> 3 LOAD_GLOBAL 0 (True)
# 6 POP_JUMP_IF_FALSE 12
#
# 9 JUMP_ABSOLUTE 3
# >> 12 POP_BLOCK
# >> 13 LOAD_CONST 0 (None)
# 16 RETURN_VALUE
dis.dis(bar)
# 0 SETUP_LOOP 3 (to 6)
#
# >> 3 JUMP_ABSOLUTE 3
# >> 6 LOAD_CONST 0 (None)
# 9 RETURN_VALUE
Edit: This is in Python 2.7.1. d0mine pointed out that the discrepancy is no longer the case in Python 3. Good to know. :)
- d0mine 15y agoThere is no difference on Python 3: >>> dis.dis(foo) 2 0 SETUP_LOOP 3 (to 6) 3 >> 3 JUMP_ABSOLUTE 3 >> 6 LOAD_CONST 0 (None) 9 RETURN_VALUE >>> dis.dis(bar) 2 0 SETUP_LOOP 3 (to 6) 3 >> 3 JUMP_ABSOLUTE 3 >> 6 LOAD_CONST 0 (None) 9 RETURN_VALUE