Linked Lists vs. Arrays: The Cache Locality Divide
Arrays store data contiguously, leveraging cache lines and hardware prefetching for fast sequential access, while linked lists scatter data, leading to frequent cache misses and drastically slower random access despite theoretical O(1) insertion at a known position.
The top 3
- Arrays' Sequential Access: 10x to 100x Faster Than Linked Lists: Arrays can be dramatically faster for sequential access, often 10x to 100x, compared to linked lists, because their contiguous memory layout allows CPUs to efficiently prefetch data into cache lines, minimizing costly main memory access.
- Cache Line Utilization: Arrays Maximize, Linked Lists Fragment: Arrays efficiently fill CPU cache lines with multiple contiguous elements, ensuring that when one element is accessed, several nearby elements are also loaded, whereas linked list nodes are scattered in memory, leading to inefficient cache line fills and more cache misses.
- Linked Lists' Edge: Fast Mid-List Inserts & Deletes: Linked lists offer a significant advantage for frequent insertions and deletions in the middle of a collection, providing O(1) time complexity once the insertion/deletion point is known, which avoids the costly O(N) data shifts and reallocations required by arrays.
Sources
Open the full topic