Rust:String::from()、 into()、to_string()哪个效率高?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wowotuo/article/details/85400413

据说rust早期版本中,String::from()、into()、to_string(),推荐前两种算法,后面一种说开销大,效率低。因此想测试一下:

一、代码

use std::thread;
use std::time::{Duration, SystemTime};
fn main() {
    println!("下面开始比较三种方法:");
    let sy_time0 = SystemTime::now();
    let n = 100000000; //1个亿次数
    for _ in 0..n {
        let _x: String = "hello".to_string();
    }
    println!(
        "to_string:() => time :{} seconds",
        SystemTime::now()
            .duration_since(sy_time0)
            .unwrap()
            .as_secs()
    );
    let sy_time1 = SystemTime::now();
    for _ in 0..n {
        let _x: String = String::from("hello");
    }
    println!(
        "string::from() => time :{} seconds",
        SystemTime::now()
            .duration_since(sy_time1)
            .unwrap()
            .as_secs()
    );

    let sy_time2 = SystemTime::now();
    for _ in 0..n {
        let _x: String = "hello".into();
    }
    println!(
        "into() => time :{} seconds",
        SystemTime::now()
            .duration_since(sy_time2)
            .unwrap()
            .as_secs()
    );

    thread::sleep_ms(500000);
}

二、测试结果

1亿次的测试结果如下:

在这里插入图片描述

也就是说,这三种方法相差无几。

to_string()方法已经经过优化了。

猜你喜欢

转载自blog.csdn.net/wowotuo/article/details/85400413