Working with arrays in V8 (performance issue)

后端 未结 2 1837
清酒与你
清酒与你 2021-01-30 22:40

I tried next code (it shows similar results in Google Chrome and nodejs):

var t = new Array(200000); console.time(\'wtf\'); for (var i = 0; i < 200000; ++i) {         


        
2条回答
  •  生来不讨喜
    2021-01-30 23:41

    If you preallocate, do not use .push because you will create a sparse array backed by a hashtable. You can preallocate sparse arrays up to 99999 elements which will be backed by a C array, after that it's a hashtable.

    With the second array you are adding elements in a contiguous way starting from 0, so it will be backed by a real C array, not a hash table.

    So roughly:

    If your array indices go nicely from 0 to Length-1, with no holes, then it can be represented by a fast C array. If you have holes in your array, then it will be represented by a much slower hash table. The exception is that if you preallocate an array of size < 100000, then you can have holes in the array and still get backed by a C array:

    var a = new Array(N); 
    
    //If N < 100000, this will not make the array a hashtable:
    a[50000] = "sparse";
    
    var b = [] //Or new Array(N), with N >= 100000
    //B will be backed by hash table
    b[50000] = "Sparse";
    //b.push("Sparse"), roughly same as above if you used new Array with N > 0
    

提交回复
热议问题