Initializing a Vec
in Rust is incredibly slow if compared with other languages. For example, the following code
let xs: Vec<u32> = vec![0u32, 1000000];
will translate to
let xs: Vec<u32> = Vec::new();
xs.push(0);
xs.push(0);
xs.push(0);
// ...
one million times. If you compare this to the following code in C:
uint32_t* xs = calloc(1000000, sizeof(uint32_t));
the difference is striking.
I had a little bit more luck with
let xs: Vec<u32> = Vec::with_capacity(1000000);
xs.resize(1000000, 0);
bit it's still very slow.
Is there any way to initialize a Vec
faster?