## 18.4 Memory locality

The key to understanding efficiency of matrix and vector representations is memory locality and reference passing versus copying.

### Memory locality

CPUs on computers bring in memory in blocks through layers of caches. Fetching from memory is much slower than performing arithmetic operations. The only way to make container operations fast is to respect memory locality and access elements that are close together in memory sequentially in the program.

### Matrices

Matrices are stored internally in column-major order. That is, an $$M \times N$$ matrix stores its elements in the order $(1,1), (2, 1), \dotsc, (M, 1), (1, 2), \dotsc, (M, 2), \dotsc, (1, N), \dotsc, (M, N).$

This means that it’s much more efficient to write loops over matrices column by column, as in the following example.

matrix[M, N] a;
// ...
for (n in 1:N) {
for (m in 1:M) {
// ... do something with a[m, n] ...
}
}

It also follows that pulling a row out of a matrix is not memory local, as it has to stride over the whole sequence of values. It also requires a copy operation into a new data structure as it is not stored internally as a unit in a matrix. For sequential access to row vectors in a matrix, it is much better to use an array of row vectors, as in the following example.

array[M] row_vector[N] a;
// ...
for (m in 1:M) {
// ... do something with row vector a[m] ...
}

Even if what is done involves a function call, the row vector a[m] will not have to be copied.

### Arrays

Arrays are stored internally following their data structure. That means a two dimensional array is stored in row-major order. Thus it is efficient to pull out a “row” of a two-dimensional array.

array[M, N] real a;
// ...
for (m in 1:M) {
// ... do something with a[m] ...
}

A difference with matrices is that the entries a[m] in the two dimensional array are not necessarily adjacent in memory, so there are no guarantees on iterating over all the elements in a two-dimensional array will provide memory locality across the “rows.”
{"ft_lang_label":"__label__en","ft_lang_prob":0.90689516,"math_prob":0.9452533,"size":2010,"snap":"2023-14-2023-23","text_gpt3_token_len":491,"char_repetition_ratio":0.107178465,"word_repetition_ratio":0.0726257,"special_character_ratio":0.26716417,"punctuation_ratio":0.17701149,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97845453,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-03-20T19:18:50Z\",\"WARC-Record-ID\":\"<urn:uuid:3c97c03c-fb9e-4834-984f-639250cfe7ba>\",\"Content-Length\":\"124010\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:b883b441-0049-44a8-8065-1a78f5e6dd74>\",\"WARC-Concurrent-To\":\"<urn:uuid:e1a78303-fc4d-4b4c-a193-95bdf1500102>\",\"WARC-IP-Address\":\"185.199.108.153\",\"WARC-Target-URI\":\"https://mc-stan.org/docs/stan-users-guide/memory-locality.html\",\"WARC-Payload-Digest\":\"sha1:6DOTOIUL2JYHF3TTXHNZX6YUZXKRRJK5\",\"WARC-Block-Digest\":\"sha1:3ZO5O5OYQ6EVGSVZIMYMPFG5I7SZQS5Y\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-14/CC-MAIN-2023-14_segments_1679296943555.25_warc_CC-MAIN-20230320175948-20230320205948-00785.warc.gz\"}"}