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



