sorted() using generator expressions rather than lists

前端 未结 8 1588
梦如初夏
梦如初夏 2020-11-30 05:31

After seeing the discussion here: Python - generate the time difference I got curious. I also initially thought that a generator is faster than a list, but when it comes to

8条回答
  •  心在旅途
    2020-11-30 06:03

    I should just add to Dave Webb's timing answer [I put in what may be an anonymous edit], that when you access an optimized generator directly, it may be much faster; much of the overhead may be the code's creation of a list or generator of its own:

    >>> timeit.timeit("sorted(xrange(1000, 1, -1))", number=10000)
    0.34192609786987305
    >>> timeit.timeit("sorted(range(1000, 1, -1))", number=10000)
    0.4096639156341553
    >>> timeit.timeit("sorted([el for el in xrange(1000, 1, -1)])", number=10000)
    0.6886589527130127
    >>> timeit.timeit("sorted(el for el in xrange(1000, 1, -1))", number=10000)
    0.9492318630218506
    

提交回复
热议问题