Sub topic 2
Arrays Versus Linked Structures
Assume you know arrays, linked lists, structs, pointers, and Big-O notation. The key question here is not only how many operations a structure needs. It is also how its memory is arranged.
Sequential access favors arrays
An array stores elements next to one another. Reading one element often brings nearby elements into the cache, a small, fast memory near the CPU. A linked list stores each node separately and follows a pointer to find the next node.
#include <stddef.h>
#include <stdio.h>
struct Node {
int value;
struct Node *next;
};
long sum_array(const int *a, size_t n) {
long sum = 0;
for (size_t i = 0; i < n; ++i)
sum += a[i];
return sum;
}
long sum_list(const struct Node *node) {
long sum = 0;
for (; node != NULL; node = node->next)
sum += node->value;
return sum;
}
int main(void) {
int values[] = {1, 2, 3, 4};
struct Node nodes[4] = {
{1, &nodes[1]}, {2, &nodes[2]},
{3, &nodes[3]}, {4, NULL}
};
printf("%ld %ld\n", sum_array(values, 4), sum_list(&nodes[0]));
}Both functions are O(n), but the array usually runs faster because its accesses are sequential and predictable.
Miss types
- A compulsory miss happens the first time data is read.
- A capacity miss happens when the working data does not fit in the cache.
- A conflict miss happens when different addresses compete for the same cache locations.
Layout inside structs
A field's alignment can cause padding, unused bytes inserted by the compiler. Put larger fields first when practical:
struct Compact {
double value;
char type;
char flags;
};Smaller structs place more useful elements in each cache line.
AoS, SoA, and hot data
An array of structs (AoS) keeps each object's fields together. It suits code that uses most fields for each object. A struct of arrays (SoA) stores each field in its own array. It suits loops that process one field across many objects.
Split hot data, used frequently, from cold data, used rarely. A compact hot structure avoids loading cold fields into the cache.
Prefetching
Hardware prefetching predicts sequential access and loads upcoming cache lines early. Regular array traversal helps it. Pointer chasing, random indexing, and large strides make prediction difficult.
Exercise
Why can an array traversal outperform a linked-list traversal when both are O(n)?
Show answer
Array elements are adjacent, so cache lines and hardware prefetching make later reads cheaper. Linked-list nodes may require separate, unpredictable memory loads.