The Missing Bit

TIL - Rust vec.resize() is slow in debug
April 25, 2020

til rust

I was doing some tinkering with OpenGL and some code I copied from the example used Vec::resize() to resize a vector. And I discovered this was terribly slow when not compiled for release.

Let’s compare the following code:

#[macro_use]
extern crate log;

fn main() {
    env_logger::init();
    let len: usize = 10_000 * 10_000 * 4;

    info!("start");

    let mut pixels: Vec<u8> = vec![];
    pixels.resize(len, 0);

    info!("end");
}

This, when run with RUST_LOG=info cargo run :

[2020-04-25T13:23:05Z INFO  resize_test] start
[2020-04-25T13:23:22Z INFO  resize_test] end

17 seconds to resize the vector!!!

Now, this code:

#[macro_use]
extern crate log;

fn main() {
    env_logger::init();
    let len: usize = 10_000 * 10_000 * 4;

    info!("start");

    let mut pixels: Vec<u8> = vec![0; len];

    info!("end");
}
[2020-04-25T13:24:46Z INFO  resize_test] start
[2020-04-25T13:24:46Z INFO  resize_test] end

Is “instant”.

The issue is not present when compiling with --release.

This is with rustc 1.40.0 (73528e339 2019-12-16)

If you wish to comment or discuss this post, just mention me on Mastodon or Twitter.

Related posts