i32, u32, u64,i64,i128,u128,(u64,u64),(i64,i64) 作为 Map Key 效率对比

原创
2020/06/29 16:24
阅读数 115

结果:

i32: 865
u32: 824
i64: 1102
u64: 1053
i128: 1385
u128: 1355
(i64, i64): 1465
(u64, u64): 1421

有符号和无符号速度基本无差别,谁放到后面执行谁的速度快一点,可能猜测跟 CPU 缓存有关系。 速度依次递减:32 < 64 < 128 < (64,64)

代码:

use std::collections::HashMap;

fn main() {

    let mut mp: HashMap<i32, bool> = HashMap::new();
    let start = std::time::Instant::now();
    for i in 0..10000_000i32 {
        mp.insert(i, true);
    }
    println!("i32: {}", start.elapsed().as_millis());


    let mut mp: HashMap<u32, bool> = HashMap::new();
    let start = std::time::Instant::now();
    for i in 0..10000_000u32 {
        mp.insert(i, true);
    }
    println!("u32: {}", start.elapsed().as_millis());

    let mut mp: HashMap<i64, bool> = HashMap::new();
    let start = std::time::Instant::now();
    for i in 0..10000_000i64 {
        mp.insert(i, true);
    }
    println!("i64: {}", start.elapsed().as_millis());


    let mut mp: HashMap<u64, bool> = HashMap::new();
    let start = std::time::Instant::now();
    for i in 0..10000_000u64 {
        mp.insert(i, true);
    }
    println!("u64: {}", start.elapsed().as_millis());


    let mut mp: HashMap<i128, bool> = HashMap::new();
    let start = std::time::Instant::now();
    for i in 0..10000_000i128 {
        mp.insert(i, true);
    }
    println!("i128: {}", start.elapsed().as_millis());


    let mut mp: HashMap<u128, bool> = HashMap::new();
    let start = std::time::Instant::now();
    for i in 0..10000_000u128 {
        mp.insert(i, true);
    }
    println!("u128: {}", start.elapsed().as_millis());


    let mut mp: HashMap<(i64, i64), bool> = HashMap::new();
    let start = std::time::Instant::now();
    for i in 0..10000_000i64 {
        mp.insert((i, i), true);
    }
    println!("(i64, i64): {}", start.elapsed().as_millis());


    let mut mp: HashMap<(u64, u64), bool> = HashMap::new();
    let start = std::time::Instant::now();
    for i in 0..10000_000u64 {
        mp.insert((i, i), true);
    }
    println!("(u64, u64): {}", start.elapsed().as_millis());
}

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部