Why is it slower to iterate over a small string than a small list?

前端 未结 3 1713
广开言路
广开言路 2020-12-22 15:57

I was playing around with timeit and noticed that doing a simple list comprehension over a small string took longer than doing the same operation on a list of small single c

3条回答
  •  囚心锁ツ
    2020-12-22 16:23

    You could be incurring and overhead for creating the iterator for the string. Whereas the array already contains an iterator upon instantiation.

    EDIT:

    >>> timeit("[x for x in ['a','b','c']]")
    0.3818681240081787
    >>> timeit("[x for x in 'abc']")
    0.3732869625091553
    

    This was ran using 2.7, but on my mac book pro i7. This could be the result of a system configuration difference.

提交回复
热议问题