node中map({})和array([])性能上有差别么?

155 阅读2分钟

问题引出

在node编写中,大家似乎都不太关心性能和内存的问题。但是对于一个主java的人来说,还是有些好奇。今天就简单测试下两者的性能差别。 本次测试主要是针对取值,或者是其中是否包含某些值的常用业务测试。我们添加一亿条数据进行测试。

function list(target) {
    let list=[];

    let start=Date.now();
    for (let i = 0; i < 100000000; i++) {
        list.push(i);
    }
    let end =Date.now();
    console.log("list int cha : "+(end-start));

    start=Date.now();
    console.log("list get result : "+list[target])
    end =Date.now();
    console.log("list get cha : "+(end-start));

    start=Date.now();
    console.log("list find result : "+list.includes(target))
    end =Date.now();
    console.log("list find cha : "+(end-start));
}

function map(target) {
    let map={};

    let start=Date.now();
    for (let i = 0; i < 100000000; i++) {
        map[i]=i;
    }
    let end =Date.now();
    console.log("map int cha : "+(end-start));

    start=Date.now();
    console.log("map get result : "+map[target])
    end =Date.now();
    console.log("map get cha : "+(end-start));

    start=Date.now();
    console.log("map find result : "+map[target])
    end =Date.now();
    console.log("map find cha : "+(end-start));
}

let target =10000000;
// let target =1000000;
// let target =100000;
// let target =10000;
list(target);
map(target);

我先验证了一下比较大的,我们查找第一千万条数据,可以看出来两者的性能还是有差别的。

list int cha : 3687
list get result : 10000000
list get cha : 0
list find result : true
list find cha : 24
map int cha : 3348
map get result : 10000000
map get cha : 0
map find result : 10000000
map find cha : 0

但是我将数据降低到十万条的时候,查找和比较已经相近了。

list int cha : 4161
list get result : 100000
list get cha : 0
list find result : true
list find cha : 0
map int cha : 3398
map get result : 100000
map get cha : 0
map find result : 100000
map find cha : 0

结论

通过测试结果,我们可以大体猜测出node的array和map存储方式应该和java大同小异,只不过node在内部进行优化;而没有像java一样,给我们不同数据结构的选择。对于小数据量来说,我们可以忽略;对于数据量比较大的情况,我们就需要注意这一点了。