Skip to content

Instantly share code, notes, and snippets.

@acro5piano
Last active July 10, 2024 10:36
Show Gist options
  • Save acro5piano/b5cb51554f948b832aa009e25111547c to your computer and use it in GitHub Desktop.
Save acro5piano/b5cb51554f948b832aa009e25111547c to your computer and use it in GitHub Desktop.
Rust to_string vs clone performance comparison
// main.rs

use std::time::Instant;

fn main() {
    let instant = Instant::now();
    let text = "".to_string();
    for _ in 1..100000000 {
        let _ = text.to_string();
        // let _ = text.clone();
    }
    println!("Elapsed time: {:.2?}", instant.elapsed());
}

Output(debug):

# to_string()
~> cargo run
   Compiling hoge v0.1.0 (/home/kazuya/sandbox/20240710_184338/hoge)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.11s
     Running `target/debug/hoge`
Elapsed time: 1.44s

# clone()
~> cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/hoge`
Elapsed time: 1.39s

In debug build, clone() is slightly faster.

Output(release):

# to_string()
~> cargo run --release
   Compiling hoge v0.1.0 (/home/kazuya/sandbox/20240710_184338/hoge)
    Finished `release` profile [optimized] target(s) in 0.09s
     Running `target/release/hoge`
Elapsed time: 316.68ms

# clone()
~> cargo run --release
    Finished `release` profile [optimized] target(s) in 0.00s
     Running `target/release/hoge`
Elapsed time: 317.22ms

No signinicant difference release build.

Tried many times and the result didn't change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment