How does drop function work?

hi. i was reading the doc and found out that every local variable that uses heap for storing data such as String, will have their data removed by drop() function at the end of the scope it was declared in that scope. then i benchmarked these 2 functions and i found out that when i call drop() function manually, it is slower! why is that? shouldn't they atleast take the same time?(the example code provided is for easy demonstartion and the example that i tested had repeated this more than 6 times and the one that called drop function manually took 120ns but the one using only {} took 80ns). the example code:

use criterion::{criterion_group, criterion_main, Criterion};

fn testdrop(){
    {
        let mut s1 = String::from("hello1");
        s1.push_str(", world!"); 
    }
}

fn testdrop2(){ 
    let mut s1 = String::from("hello1");
    s1.push_str(", world!"); 
    drop(s1);
}
fn criterion_benchmark(c: &mut Criterion) {
    c.bench_function("testdrop 1", |b| b.iter(|| testdrop()));
    c.bench_function("testdrop 2", |b| b.iter(|| testdrop2()));
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

the result was as following:

testdrop 1              time:   [14.118 ns 14.255 ns 14.399 ns]
Found 1 outliers among 100 measurements (1.00%)
  1 (1.00%) high severe

testdrop 2              time:   [21.966 ns 22.190 ns 22.435 ns]
Found 2 outliers among 100 measurements (2.00%)

i used criterion for testing:

criterion = { version = "0.5", features = ["html_reports"] }

Welcome to measurement error :slight_smile:

Both functions compile to exactly the same code, other than the function name (and the choice of a label name): https://rust.godbolt.org/z/KP63WPTq8

Try running them in the other order -- I suspect what you're actually measuring here is your allocator's behaviour.

18 Likes