What is the difference between range and xrange functions in Python 2.X?

后端 未结 28 2081
深忆病人
深忆病人 2020-11-22 03:14

Apparently xrange is faster but I have no idea why it\'s faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about

28条回答
  •  鱼传尺愫
    2020-11-22 03:56

    The difference decreases for smaller arguments to range(..) / xrange(..):

    $ python -m timeit "for i in xrange(10111):" " for k in range(100):" "  pass"
    10 loops, best of 3: 59.4 msec per loop
    
    $ python -m timeit "for i in xrange(10111):" " for k in xrange(100):" "  pass"
    10 loops, best of 3: 46.9 msec per loop
    

    In this case xrange(100) is only about 20% more efficient.

提交回复
热议问题