Select data structures and algorithms that optimize for the specific use case rather than defaulting to generic collections. Consider computational complexity, memory usage, and access patterns when making these choices.
Key principles:
HashMap<String, i32>
instead of Vec<(String, i32)>
[u8; 32]
for commit hashes instead of Vec<u8>
i.count_ones()
instead of casting to usize for bit countingpeg
for grammar parsing)Active = 1
instead of Active = 0
checked_sub()
and match on the result instead of separate comparison and subtractionExample of efficient data structure selection:
// Instead of this:
let chain_ids_and_ids: Vec<(String, i32)> = fetch_data();
// Use this for lookups:
let chain_lookup: HashMap<String, i32> = fetch_data().into_iter().collect();
// Instead of this for bit counting:
sync_committee_bits.iter().map(|i| *i as usize).sum::<usize>()
// Use this:
sync_committee_bits.iter().map(|i| i.count_ones() as usize).sum::<usize>()
Enter the URL of a public GitHub repository