0

I've searched for this and was surprised not to find this. My question regards specifically to FORTRAN (95), but I assume it is not different for other languages:

If I want to access an array in reverse order (last value/index, going backwards to the first value/index), would that be slower (in any meaningful way) than going forward (first value/index to last value/index)? I could, of course, just test it out - but I'm interested knowing the reason and not just the yes/no part.

Just to point out, the question refers a 1D array, so this has nothing to do with indexing order (i,j,k vs k,j,i) or anything of that nature.

Thanks!

  • What are you trying to do with it? How big is the array? Off the top of my head, probably not much difference. But only testing with your specific use case will tell you for sure. – Ross Mar 04 '18 at 03:59
  • CPUs tend to fill their caches by reading the data immediately *after* whatever you access on the assumption you will move forwards through data, so you will probably incur lots of cache misses which may or may not make a big difference, depending on how much processing you do with each element and the relative speed of the different levels of your CPU's caches. Measure it! – Mark Setchell Mar 04 '18 at 08:58
  • If it was a problem, you could may get around it if, say, you knew your array held N elements and your cache could hold 16 array elements. Then you could read element N-15 (thereby fetching the last 16 elements into cache) and process the last 16 elements of your array in reverse order. Then read element N-31 and do the next 16 and so on... – Mark Setchell Mar 04 '18 at 09:07
  • All common CPUs of the last decade have at least one read buffer for backward reads. Most have a relatively small number of backward buffers (I don't know the technical term), so if you access several backward arrays, you will exceed the number which can be prefetched. The usual writes with read for ownership would presumably use up read buffers. – tim18 Mar 04 '18 at 13:24
  • Thank you all for your comments! The caching does seem like the logical bottleneck here. – TheWhitestOfFangs Mar 04 '18 at 21:49
  • 2
    https://stackoverflow.com/questions/1950878/c-for-loop-indexing-is-forward-indexing-faster-in-new-cpus – Anthony Scemama Mar 05 '18 at 13:59

0 Answers0