what we have to prefer any() or for , on vec and array iterate operations, which is faster
You should really use the one that more closely describes what you're doing (which will probably be any
). It should optimize to pretty much the same thing as a for loop with break on a condition.
If you're in a situation where every bit of performance matters, profiling will tell you if there's any difference at all and which is faster with your code.
In general, in most cases, internal iteration (i.e. function with callback, like any
or fold
) will be not slower than external one (i.e. for
loop or manually calling next
). I'm not saying "faster", since they can (and usually will) be optimized down to the same thing, but at least you should not expecting any
to be a pessimization, and in some cases it will actually be better.
Of course, the only real answer is "benchmark it with the realistically-looking load", since any other answer will be nothing more than speculation.
Use any()
, because it's shorter and makes the intention clearer.
The performance is exactly the same. If you have a more complex case, you can check it using https://rust.godbolt.org (but remember to add -O
to compiler options field!) or cargo asm
to see whether there's any difference.
If you're working on slices, it's not going to matter. LLVM is most optimized for that, and for loops over iterators or internal iteration on the iterators so going to perform the same.
So use any
since it's clearer. And for some other iterators it'll be faster, as @Cerber-Ursi said.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.