4 ms·
``` It also has no inherent knowledge about how to iterate over any particular structure: it doesn’t know how to iterate over lists, or ranges of numbers. Rathe
by drbig 2y ago
```
It also has no inherent knowledge about how to iterate over any particular structure: it doesn’t know how to iterate over lists, or ranges of numbers. Rather it knows that iterating has to answer two questions:
is there more?
what is the next thing?
In addition it knows how to ask another question:
is there any information I can use to make asking the first two questions faster?
```
This approach sounds so good. Focus on what is needed to solve the main task. Don't do less, but please don't do more. And... Do Not Assume.
- Joker_vD 2y agoYes, and that's why Java and C# use pretty much this exact approach (without the acceleration part, to be fair) for their Iterator/IEnumerator that power their for-each loops.
- Someone 2y ago> Rather it knows that iterating has to answer two questions: > is there more? > what is the next thing? > This approach sounds so good. Does it? I think separating the checking for presence of a next value (hasNext) from retrieving that value (next) isn’t the best idea, and most performant implementations will secretly already do the latter when asked the former, but then have to add an additional check in the “what is the next thing?” method in case there isn’t any. That’s doing extra work in cases where the program only is interested in whether there are more items, but that rarely happens, doesn’t it? Yes, good compilers can often combine the two through inlining and the like, but why make the compiler do extra work if you also could have “what is the next thing, if any?” as the sole method? (That’s more or less what IEnumerator.MoveNext does in C# (https://learn.microsoft.com/en-us/dotnet/api/system.collections.ienumerator.movenext?view=net-8.0 https://learn.microsoft.com/en-us/dotnet/api/system.collecti...))