Performance Advantages to Iterators?

后端 未结 9 1797
梦毁少年i
梦毁少年i 2020-11-28 10:45

What (if any) performance advantages are offered by using iterators. It seems like the \'Right Way\' to solve many problems, but does it create faster/more memory-conscious

9条回答
  •  醉酒成梦
    2020-11-28 11:21

    Iterators will be faster and have better memory efficiency. Just think of an example of range(1000) vs xrange(1000). (This has been changed in 3.0, range is now an iterator.) With range you pre-build your list, but xrange is an iterator and yields the next item when needed instead.

    The performance difference isn't great on small things, but as soon as you start cranking them out getting larger and larger sets of information you'll notice it quite quickly. Also, not just having to generate and then step through, you will be consuming extra memory for your pre-built item whereas with the iterator, only 1 item at a time gets made.

提交回复
热议问题