| 1 | use defer_drop::DeferDrop; |
| 2 | use std::iter::repeat_with; |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | fn timer(f: impl FnOnce()) -> Duration { |
| 6 | let start = Instant::now(); |
| 7 | f(); |
| 8 | start.elapsed() |
| 9 | } |
| 10 | |
| 11 | fn main() { |
| 12 | println!("Allocating a ridiculously large vector"); |
| 13 | let vec1: Vec<Vec<String>> = repeat_with(|| { |
| 14 | repeat_with(|| "Hello, World".to_string()) |
| 15 | .take(1000) |
| 16 | .collect() |
| 17 | }) |
| 18 | .take(1000) |
| 19 | .collect(); |
| 20 | |
| 21 | println!("Duplicating that vector"); |
| 22 | let vec2 = vec1.clone(); |
| 23 | let defer_vec1 = DeferDrop::new(vec1); |
| 24 | |
| 25 | println!("Dropping the vectors"); |
| 26 | |
| 27 | let vec1_timer = timer(move || drop(defer_vec1)); |
| 28 | let vec2_timer = timer(move || drop(vec2)); |
| 29 | |
| 30 | println!("Duration of deferred drop: {:?}", vec1_timer); |
| 31 | println!("Duration of foreground drop: {:?}", vec2_timer); |
| 32 | } |