I have a method that looks as follows:
fn func(
&self,
) -> Something {
let v: Vec<u8> = ...1mln entries...;
...do something with that vec...
Something::default()
}
After some profiling, I realized that this function is spending around 300ms for dropping that Vec<u8>. I was able to measure it by doing:
use std::time::Instant;
...
fn func(
&self,
) -> Something {
let v: Vec<u8> = ...1mln entries...;
...do something with that vec...
let drop_t0 = Instant::now();
drop(v);
println!("[drop_elapsed] {}ms", drop_t0.elapsed().as_millis());
Something::default()
}
I wanted this func to be faster for this cleanup so I came up with the following:
use tokio::task;
...
fn func(
&self,
) -> Something {
let v: Vec<u8> = ...1mln entries...;
...do something with that vec...
task::spawn(async move {
drop(v);
});
Something::default()
}
And indeed I achieved what I wanted. I'm still a Rust newbie, so I wanted to know how bad is this. Are there other alternatives that are more idiomatic? One idea would be to make v as a field of the struct and recycle it every time, but it doesn't feel natural.
EDIT:
The Vec is not actually a Vec<u8>, but it's a Vec<CustomStruct> where:
pub struct CustomStruct {
pub field: Vec<Option<Vec<u8>>>,
}
It's built from the response of a server. Then in the function, I do some manipulation and after that, I just don't need it anymore.