JS往數(shù)組中添加項性能分析

字號:


    這篇文章主要介紹了JS往數(shù)組中添加項性能分析的相關(guān)資料,需要的朋友可以參考下
    比較了4種可以向數(shù)組添加項的方法之間的性能:
    使用索引器添加
    代碼如下:
    console.time("index");
    var a = [];
    for (var i = 0, l = times; i < l; i++) {
    a[i] = i;
    }
    console.timeEnd("index");
    使用push方法
    代碼如下:
    console.time("push");
    var a = [];
    for (var i = 0, l = times; i < l; i++) {
    a.push(i);
    }
    console.timeEnd("push");
    使用concat方法
    代碼如下:
    console.time("concat");
    var a = [];
    for (var i = 0, l = times; i < l; i++) {
    a.concat(i);
    }
    console.timeEnd("concat");
    使用concat方法,參數(shù)為數(shù)組
    代碼如下:
    console.time("concat with array");
    var a = [];
    for (var i = 0, l = times; i < l; i++) {
    a.concat([i]);
    }
    console.timeEnd("concat with array");
    把times設(shè)置為10000(萬)次:
    代碼如下:
    index: 0.310ms
    push: 1.476ms
    concat: 8.911ms
    concat with array: 2.261ms
    把times設(shè)置為100000(十萬)次:
    代碼如下:
    index: 1.967ms
    push: 11.980ms
    concat: 70.410ms
    concat with array: 28.292ms
    把times設(shè)置為1000000(百萬)次:
    代碼如下:
    index: 138.559ms
    push: 93.074ms
    concat: 608.768ms
    concat with array: 243.371ms
    把times設(shè)置為10000000(千萬)次:
    代碼如下:
    index: 1473.733ms
    push: 611.636ms
    concat: 6058.528ms
    concat with array: 2431.689ms
    總結(jié)
    該結(jié)論僅受用與chrome瀏覽器
    concat方法的執(zhí)行效率是最慢的
    相比兩種concat方法的傳參,當(dāng)接受參數(shù)為數(shù)組時,執(zhí)行效率要高于接受參數(shù)為非數(shù)組
    索引器多數(shù)情況下執(zhí)行效率要高于push方法
    當(dāng)執(zhí)行次數(shù)越來越多時,索引器的執(zhí)行效率開始不如push方法
    瀏覽器對比
    感謝網(wǎng)友指出,本人經(jīng)驗不足,在這里補上瀏覽器之間的橫向?qū)Ρ?BR>    首先是使用concat方法,在ie和firefox中,參數(shù)為數(shù)組執(zhí)行效率反而別參數(shù)為非數(shù)組慢一點,但差異并不大
    然后index和push的方法比concat快是肯定的了,在ie中使用index方法始終要比push快,在firefox中push略勝一籌但差異不大
    比較3個瀏覽器之間index和push方法的執(zhí)行效率差異是巨大的,firefox的執(zhí)行效率要比ie和chrome高出不少,在百萬次的情況下,基本快10倍,ie相比另外兩者最慢
    以下為百萬次的結(jié)果:
    代碼如下:
    // firefox
    index: timer started
    index: 229.79ms
    push: timer started
    push: 205.12ms
    concat: timer started
    concat: 2136.99ms
    concat with array: timer started
    concat with array: 2365.18ms
    ```
    代碼如下:
    // ie
    index: 2,533.744 毫秒
    push: 3,865.979 毫秒
    concat: 4,303.139 毫秒
    concat with array: 4,792.208 毫秒
    本文僅僅是探討JS的性能,通過對比加深小伙伴們對javascript的理解,希望大家能夠喜歡。