Spatial Locality
Computer scientists like to refer to this idea as either spatial locality or locality of reference. That is, code is faster if it keeps accessing data that is near other data that was accessed recently. So, if our code accessed array[0], it’s great if the next data the computer grabs is array[1] or array[2]. Because array[1] and array[2] are near array[0], they’re likely already in the cache.
Understanding the computer’s caching hardware allows us to avoid these pitfalls and write faster code. In this case, the difference is significant. When I benchmark summing a two-dimensional array of size 10,000, Version One takes about 9 seconds, while Version Two takes roughly 18 seconds. Leveraging spatial locality, in this case, makes ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access