python - Why is reversing a list with slicing slower than reverse iterator -


there @ least 2 ways reverse list in python, iterator approach faster (at least in python 2.7.x). want understand contributes speed difference.

>>> x = range(1000) >>> %timeit x[::-1] 100000 loops, best of 3: 2.99 per loop >>> %timeit reversed(x) 10000000 loops, best of 3: 169 ns per loop 

i suspect speed difference due @ least following:

  1. reversed written in c
  2. reversed iterator, less memory overhead

i tried use dis module better view of these operations, wasn't helpful. had put these operations in function 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 happens during slicing operation, there lot of memory overhead? maybe slicing implemented in pure python?

that's because reversed returns iterator while slicing returns whole list.

>>> lis = range(10) >>> lis[::-1] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> reversed(lis) <listreverseiterator object @ 0x909dd0c> 

you've use list() convert iterator whole list:

>>> lis = range(10**5) >>> %timeit lis[::-1] 100 loops, best of 3: 2.8 ms per loop >>> %timeit list(reversed(lis)) 100 loops, best of 3: 3.13 ms per loop 

help on reversed:

>>> reversed? type:       type string form:<type 'reversed'> namespace:  python builtin docstring: reversed(sequence) -> reverse iterator on values of sequence  return reverse iterator 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -