Why doesn't clone get optimised out here?
⚓ Rust 📅 2025-09-26 👤 surdeus 👁️ 7use rand::Rng;
use std::time::SystemTime;
fn main() {
    let mut rng = rand::rng();
    
    
    let a: Vec<i64> = (0..1000000).into_iter().map(|_i| rng.random_range(0..2i64.pow(32))).collect();
   
    
    let now = SystemTime::now();
    let s1: i64 = a.iter().sum();
    let t1 = now.elapsed().unwrap();
    println!("s1: {:?}, t1: {t1:?}", s1);
    
    let now = SystemTime::now();
    // Why does this clone not get optimised out?
    let s2: i64 = a.clone().iter().sum();
    let t2 = now.elapsed().unwrap();
    println!("s2: {:?}, t2: {t2:?}", s2);
    
    let now = SystemTime::now();
    let s3: i64 = a.iter().cloned().sum();
    let t3 = now.elapsed().unwrap();
    println!("s3: {:?}, t3: {t3:?}", s3);
}
Shouldn't the compiler be smart enough to optimize out the a.clone() in the second timing section above?
The timing output seems to show that it's cloning the entire vec and then doing the sum reduction, rather than correctly avoiding cloning the entire vec like section 3.
With no mutable refs taken shouldn't this be a trivial optimization?
2 posts - 2 participants
🏷️ Rust_feed