Which of these two dimensional array are advantageous to use and why?

后端 未结 5 1930
故里飘歌
故里飘歌 2021-01-26 18:54

In a facebook group, I saw a question like :

If a row dominated two dimensional array in the following which one is advantage and why?

         


        
5条回答
  •  终归单人心
    2021-01-26 19:31

    When the CPU wants to read data/code from the memory, chunks of data or moved from the memory to cache. Cache is much faster than RAM and much more expensive, so you have little of it. The idea behind this is that usually when you read one part of memory, you probably read other parts that are close to it.

    In method a, you read the array row by row, and therefore you keep the locality. That is, on the first read from a row, the row is loaded in cache, and the rest of the row is read from cache (cache hit), so you have a high cache hit rate which is good.

    In method b, you are deliberately accessing the array in a non contiguous way, so you get a lot of cache misses, and you need to keep reading from memory all the time.

提交回复
热议问题