There are at least two ways to reverse a list in Python, but the iterator approach is much faster (at least in Python 2.7.x). I want to understand what contributes to this speed difference.
>>> x = range(1000)
>>> %timeit x[::-1]
100000 loops, best of 3: 2.99 us per loop
>>> %timeit reversed(x)
10000000 loops, best of 3: 169 ns per loop
I suspect the speed difference is due to at least the following:
reversed
is written in Creversed
is an iterator, so less memory overhead
I tried to use the dis
module to get a better view of these operations, but it wasn't too helpful. I had to put these operations in a function to disassemble them.
>> def reverselist(_list):
... return _list[::-1]
...
>>> dis.dis(reverselist)
2 0 LOAD_FAST 0 (_list)
3 LOAD_CONST 0 (None)
6 LOAD_CONST 0 (None)
9 LOAD_CONST 1 (-1)
12 BUILD_SLICE 3
15 BINARY_SUBSCR
16 RETURN_VALUE
>>> def reversed_iter(_list):
... return reversed(_list)
...
>>> dis.dis(reversed_iter)
2 0 LOAD_GLOBAL 0 (reversed)
3 LOAD_FAST 0 (_list)
6 CALL_FUNCTION 1
9 RETURN_VALUE
What all exactly happens during a slicing operation, is there a lot of memory overhead? Maybe slicing is implemented in pure Python?