4 ms·
the correct way/idiom to reverse iterate an array is for (size_t i = length; i-- > 0; )... It's surprising how often the issue pops, it works well with both
by xxs 4y ago
the correct way/idiom to reverse iterate an array is
for (size_t i = length; i-- > 0; )...
It's surprising how often the issue pops, it works well with both signed and unsigned integers.
(edit) I've started with one based indexing (basic)... mixed with 0 based (assembly), more 1 based (pascal), then more stuff (all zero based). I am, yet, to see a real advantage of a one based indexing... after the initial process.
- empiricus 4y agoIs this cache friendly?
- msk-lywenn 4y agoIt’s not. It was nice on architectures were cache didn’t matter much and were subtracting and comparing to zero was just one instruction (looking at you old core ARM)
- sgtnoodle 4y agoSure, why wouldn't it be? As far as a cache is concerned, I don't think reverse sequential iteration would be any different than forward sequential. The actual RAM accesses may be less optimal if there's some speculative pre-fetching with assumed forward sequential access, but that's conjecture.
- chii 4y agoi would suspect that the cache prefetch/prediction could use the "velocity" of the memory access to predict the next access; so if the access pattern was going backwards, the "velocity" would be negative, but prefetching would still work if they just followed the predicted pattern.
- ehvatum 4y agoWith some exceptions, hardware prefetch works in terms of ascending accesses. To learn if a particular CPU will prefetch for descending access, benchmarking is essential. Best to use soft prefetch calls if performance is critical.
- ehvatum 4y agoIt is not, unless your compiler is smart enough to recognize reverse iteration and prefetch appropriately. If performance matters, you should experiment with __builtin_prefetch, which is available in clang and GCC.