# Data locality

One of the questions in {numref}`how-do-we-simulate-moving-shapes` was about the trade-offs of different data structures, e.g., array vs struct.

How far data is placed from each other can affect performance.

## Array of structs vs struct of arrays

```{literalinclude} ../code/how-data-locality-affects-performance.c
:language: c
```
Output on my computer:
```
AoS sum: -893370230, time: 1.249000 ms
SoA sum: 863692085, time: 0.674000 ms
```
Output on the cloud server:
```{literalinclude} ../code/how-data-locality-affects-performance.txt
:language: c
```



:::{commons-figure} https://commons.wikimedia.org/wiki/File:Shared_private.png
:figwidth: 40%
:align: right
When data is read, it is stored on many layers of cache, which become smaller in size towards the processor cores. 
:::

Struct of arrays achieve a better performance, because x's are near each other.

## Appendix

This is related to how memory is organized in processors.
:::{wpd} cache
:id: Cache (computing)
a hardware of software component that stores data so that future requests for that data can be served faster
:::

<!--
For example my computer has the following caches:
```
$ lscpu
...
Caches (sum of all):         
  L1d:                       352 KiB (10 instances)
  L1i:                       576 KiB (10 instances)
  L2:                        6.5 MiB (4 instances)
  L3:                        12 MiB (1 instance)
```
-->

