liveBook · Manning

Data locality

As explained in Idiomatic Rust

Data locality is the tendency for a program to access data near recently accessed or related data in memory.

Data locality favors accessing data near recently used or related data. A Vec stores elements contiguously, which can improve CPU-cache friendliness and simplify element movement. Other structures can outperform it for some workloads, so benchmark before choosing a more complex alternative. section 10.4

Listing 10.7 Benchmarking Vec, HashSet, and LinkedList for appending
#[bench]
fn vec_append(b: &mut Bencher) {
    b.iter(|| {
        let mut nums: Vec<i32> = Vec::new();
        for n in 0..1_000_000 {
            nums.push(n);
        }
    });
}

#[bench]
fn list_append(b: &mut Bencher) {
    b.iter(|| {
        let mut nums: LinkedList<i32> = LinkedList::new();
        for n in 0..1_000_000 {
            nums.push_back(n);
        }
    });
}

#[bench]
fn set_append(b: &mut Bencher) {
    b.iter(|| {
        let mut nums: HashSet<i32> = HashSet::new();
        for n in 0..1_000_000 {
            nums.insert(n);
        }
    });
}

Compare append benchmarks for Vec, HashSet, and LinkedList; the results illustrate performance differences but do not isolate data locality as their cause. section 10.4

How Idiomatic Rust covers it

How deep it goes
Defines locality through nearby memory access and links contiguous storage to cache behavior, without detailing hardware internals.
Examples
Compares append, search, and removal timings for Vec, HashSet, and LinkedList.
What you can do after
Evaluate collection choices by benchmarking workloads, and favor Vec when unsure.
How it connects
Connects data locality with Vec, CPU caches, main memory, HashSet, and LinkedList.

Also explained in

Compare how 4 books explain data locality →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.