Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to improve Vec initialization time?

Tags:

rust

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?

like image 711
André Wagner Avatar asked Jul 17 '26 17:07

André Wagner


1 Answers

You are actually performing different operations. In Rust, you are allocating an array of one million zeroes. In C, you are allocating an array of one million zero-length elements (i.e. non-existent elements). I don't believe this actually does anything, as DK commented on your question and pointed out.

Also, Running the code you presented verbatim gave me very comparable times on my laptop when optimizing, however this is probably because the vector allocation in Rust is being optimized away, as the variable is never used.

cargo build --release
time ../target/release/test

real   0.024s 
usr    0.004s
sys    0.008s

and the C:

gcc -O3 test.c 
time ./a.out

real   0.023s
usr    0.004s
sys    0.004s`

Without --release, the Rust performance drops, presumably because the allocation actually happens. Note that calloc() also looks to see if the memory is zeroed out first, and doesn't reset the memory if it is already set to zero. This makes the execution time of calloc() somewhat reliant on the previous state of your memory.

like image 196
Alex Hansen Avatar answered Jul 20 '26 07:07

Alex Hansen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!