Performance Patterns
Borrow Slice
Read Without Copying
Borrowing a slice lets a helper read part of a collection without cloning the data.
Program
Play the program to choose how many numbers the helper reads from the borrowed slice.
borrow_slice.rs
fn main() {
let limit = ;
let values = [3, 4, 5, 6];
let total = sum_prefix(&values, limit);
println!("sum={total}");
}
fn sum_prefix(values: &[i32], limit: usize) -> i32 {
values[..limit].iter().sum()
}
fn main() {
let limit = ;
let values = [3, 4, 5, 6];
let total = sum_prefix(&values, limit);
println!("sum={total}");
}
fn sum_prefix(values: &[i32], limit: usize) -> i32 {
values[..limit].iter().sum()
}
fn main() {
let limit = ;
let values = [3, 4, 5, 6];
let total = sum_prefix(&values, limit);
println!("sum={total}");
}
fn sum_prefix(values: &[i32], limit: usize) -> i32 {
values[..limit].iter().sum()
}
slice
`&values[..limit]` borrows part of the array instead of allocating another collection.
iterator
`iter().sum()` reads borrowed values and computes a result.
boundary
The helper accepts any `&[i32]`, so callers can pass arrays, vectors, or slices.