Printing a variable somehow improving performance?

⚓ Rust    📅 2025-07-17    👤 surdeus    👁️ 9      

surdeus

Warning

This post was published 61 days ago. The information described in this article may have changed.

I've been doing some testing and stumbled upon something interesting.

The following function takes around 1600ms to sort a vector of 100 000 elements

fn sort(values: &mut [u32]) {
    let mut swaps: u64 = 0;
    let mut i = 1;
    let len = values.len();
    while i < len {
        let mut j = i;
        while j > 0 && values[j-1] > values[j] {
            swaps += 1;
            values.swap(j, j-1);
            j -= 1
        }
        i += 1
    }
    //println!("{swaps}")
}

But after uncommenting the print statement, the time drops to 1400ms

fn sort(values: &mut [u32]) {
    let mut swaps: u64 = 0;
    let mut i = 1;
    let len = values.len();
    while i < len {
        let mut j = i;
        while j > 0 && values[j-1] > values[j] {
            swaps += 1;
            values.swap(j, j-1);
            j -= 1
        }
        i += 1
    }
    println!("{swaps}")
}

any thoughts on what could be causing this discrepancy?

9 posts - 4 participants

Read full topic

🏷️ rust_feed