C/C++遍历二维数组,列优先(column-major)比行优先(row-major)慢,why?
简单粗暴的答案:存在Cache机制!
稍微啰嗦一点:CPU访问内存(读/写,遍历数组的话主要是读),不是每次都直接从内存上操作,而是先看Cache里是否有所指定地址的值!
这个问题,stackoverflow上有人问过的,结论是:CPU读取内存某地址处的值,并不是每次都去内存中取出来,有时候会从cache里读取。当初次访问数组的时候,会把连续一块(chunk)内存地址上的值都读到cache里(比如,64字节),后续CPU接受到一个内存地址要读取数据时,先看cache里有没有,没有的话再去内存上取。
关键句:The important factor is that the cache doesn't contain individual bytes or words, it holds chunks of adjacent memory, known as a cache-line, typically 64-bytes in size. So when address X is in the cache the CPU probably doesn't need to pre-emptively fetch X+1 because it has probably already got it (except in the case where X is the last byte in a cache-line, in which case it probably will have pre-fetched the next cache-line).
时间: 2024-10-26 11:01:21