4 ms·
> 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 th
by 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...))