Why would iterating over a List be faster than indexing through it?

后端 未结 5 1700
小蘑菇
小蘑菇 2020-12-12 11:38

Reading the Java documentation for the ADT List it says:

The List interface provides four methods for positional (indexed) access to list elements. Li

5条回答
  •  鱼传尺愫
    2020-12-12 12:22

    Iterating over a list with an offset for the lookup, such as i, is analogous to Shlemiel the painter's algorithm.

    Shlemiel gets a job as a street painter, painting the dotted lines down the middle of the road. On the first day he takes a can of paint out to the road and finishes 300 yards of the road. "That's pretty good!" says his boss, "you're a fast worker!" and pays him a kopeck.

    The next day Shlemiel only gets 150 yards done. "Well, that's not nearly as good as yesterday, but you're still a fast worker. 150 yards is respectable," and pays him a kopeck.

    The next day Shlemiel paints 30 yards of the road. "Only 30!" shouts his boss. "That's unacceptable! On the first day you did ten times that much work! What's going on?"

    "I can't help it," says Shlemiel. "Every day I get farther and farther away from the paint can!"

    Source.

    This little story may make it easier to understand what is going on internally and why it is so inefficient.

提交回复
热议问题