Contiguous Data Structures: Boosting Spatial Locality
Data structures like arrays, which store elements sequentially in memory, inherently maximize spatial locality. This allows the CPU to load multiple elements into a single cache line when one is accessed, leading to significantly faster processing compared to non-contiguous structures like linked lists.
The top 3
- Top 3 Contiguous Structures for Cache Hits: Raw arrays, `std::vector` (C++), and fixed-size arrays (`std::array`) are prime examples of contiguous data structures, guaranteeing sequential memory layout that directly optimizes for CPU cache lines and maximizes cache hits.
- Cache Line Mechanism: Contiguous Data's Speed Engine: When a CPU accesses one element of a contiguous data structure, it typically fetches an entire cache line (commonly 64 bytes on x86 systems), bringing up to 8 `long` integers or 16 `int`s into the fast cache simultaneously, making subsequent accesses to neighboring elements significantly faster.
- Contiguous vs. Linked Lists: Up to 100x Speed Advantage: Iterating over contiguous arrays can achieve a performance speedup of 10x to 100x compared to linked lists for large datasets, primarily due to arrays' superior spatial locality, which minimizes cache misses and optimizes CPU prefetching.
Sources
Open the full topic