Pre-allocation of memory for a string

Rust

In this example I am trying to show how pre-allocation of memory for a string can improve speed. However in this example I can only see 3% time difference which I think is meaningless.

examples/pre-allocation/src/main.rs

macro_rules! prt {
    ($var:expr) => {
        println!(
            "{:10} {:10} {:p} {:15?}",
            $var.len(),
            $var.capacity(),
            &$var,
            $var.as_ptr(),
        );
    };
}

fn main() {
    let len = 100_000_000;
    {
        let start = std::time::Instant::now();
        let mut text = String::new();
        
        for i in 0..len {
            text.push_str("x");
            let _t = String::from("x"); 
            if i == 0 {
                prt!(text);
            }
        }
        prt!(text);
        println!("{:?}", start.elapsed());
        println!("len: {}", text.len());    
    }

    println!();

    {
        let start = std::time::Instant::now();
        let mut text = String::with_capacity(len);
        for i in 0..len {            
            text.push_str("x");
            let _t = String::from("x");
            if i == 0 {
                prt!(text);
            }
        }
        prt!(text);
        println!("{:?}", start.elapsed());
        println!("len: {}", text.len());
    }

}

examples/pre-allocation/out.txt

         1          8 0x7ffe80bc9d20  0x64c4d419bb80
 100000000  134217728 0x7ffe80bc9d20  0x704611600010
11.727765301s
len: 100000000

         1  100000000 0x7ffe80bca4e0  0x70461b800010
 100000000  100000000 0x7ffe80bca4e0  0x70461b800010
11.367938399s
len: 100000000


Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo