fn main() {
let arr = [10, 20, 30];
for i in 0..arr.len() {
println!("{:p}", &arr[i]);
}
}Arrays in Rust store elements in contiguous memory locations. Printing the address of each element shows addresses increasing by the size of each element (i32 is 4 bytes).
use std::rc::Rc;
struct Node {
value: i32,
next: Option<Rc<Node>>,
}
fn main() {
let node3 = Rc::new(Node { value: 30, next: None });
let node2 = Rc::new(Node { value: 20, next: Some(node3.clone()) });
let node1 = Rc::new(Node { value: 10, next: Some(node2.clone()) });
let mut current = Some(node1.clone());
while let Some(node) = current {
println!("{:p}", Rc::as_ptr(&node));
current = node.next.clone();
}
}Each linked list node is allocated separately on the heap, so their memory addresses are not contiguous and appear random.
Arrays store elements next to each other in memory, so accessing one element loads nearby elements into cache, speeding up access. Linked lists have nodes scattered in memory, causing more cache misses.
struct Node {
value: i32,
next: Option<Box<Node>>,
}
fn main() {
let node3 = Box::new(Node { value: 30, next: None });
let node2 = Box::new(Node { value: 20, next: Some(node3) });
let node1 = Box::new(Node { value: 10, next: Some(node2) });
// Print addresses
let mut current = Some(&node1);
while let Some(node) = current {
println!("{:p}", &**node);
current = node.next.as_ref().map(|b| &**b);
}
}Box allocates each node separately on the heap, so nodes are not stored contiguously. This causes non-contiguous memory layout for linked lists.
Arrays store elements contiguously, reducing memory fragmentation and improving cache hits. Linked lists allocate nodes separately, causing fragmentation and poor cache performance.
