Performance Advantages to Iterators?

后端 未结 9 1784
梦毁少年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条回答
  •  萌比男神i
    2020-11-28 11:17

    There is one answer that I think confuses the concept of generator and iterator a little bit. So I decided to give a try answering this question with a metaphor example.

    I'm working at a kitchen, my boss give me a task of adding up the weight of 10 (or 100 or a million) breads. I have a scale and a calculator( magic tricks of my algorithmn). Below are the iterable object, generator, iterator, approach difference:

    1. Iterable object: Each bread is stored in one box(memory), I weigh the first (or the 0th) bread, put down its weight, and put the bread back to the box, then go to the next one, weigh it and put it back, on and on, etc, etc. In the end, I got the overall weight, and the 10 (100 or million) breads are still there in their boxes.

    2. Generator: There are not enough boxes to store all these bread, So I asked for the help of a baker(the generator), he makes the first bread, give it to me, I weigh it, put the result down, throw that bread away and ask him for another one,on and on, etc, until I got the last bread (or maybe the baker runs out of flour). In the end, I have the result, none of the bread is there. But who cares, my boss only asks me to weigh these breads, he didn't say I cannot throw them away ( what a brilliant busboy).

    3. Iterator: I ask someone(iterator) to help me move first bread onto the scale, I weigh it, put the result down. This someone would go grab the next one for measuring, on and on, etc. I actually have no idea if someone (iterator) get the bread from a box or from a baker. Eventually, I got the overall weight, it doesn't matter to me.

    Anyway, to sum up:

    1. Iterable object need some memory to store data to start with.In the end, data is still there.

    2. Generator wouldn't need memory to store data to start with, it generates data on the go.

    3. Iterator is a channel between algorithm and its data. This data may already been there and stored in memory or may be generated on the go by a generator. In the first case, that memory would be freed bit by bit as iterator keeps iterating. So I agree a lot with above answer that iterator is good because of its abstraction that enables isolation of algorithm and data.

    python doesn't exactly work like this. Hope it help clarify a little bit.

提交回复
热议问题