Array-like object in javascript

后端 未结 6 823
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 21:52

Looking through the dom.js source from the Closure library I found this (in goog.dom.getElementsByTagNameAndClass_):

if (opt_class) {
var arrayL         


        
6条回答
  •  失恋的感觉
    2020-12-09 22:42

    In this case, my guess would be that arrayLike[len++] = el is an optimization over actualArray.push(el). However, after doing a simple benchmark (code provided below results), it appears that this method is actually slower than using a standard array using the push method as well as with same construction technique.

    Results (from OS X 10.5.8, FF 3.5.6) *:

    push construction:        199ms (fastest)
    indexed construction:     209ms
    associative construction: 258ms (slowest)
    

    In conclusion, why Closure is using an associative array in this case is beyond me. There may likely be a reason (for instance, this technique may perform better in Chrome, or less dubiously, this technique may perform better in future releases of JavaScript engines in general), but I don't see a good reason in this case.

    * A mean was not provided because the times varied from test run to test run, but consistently resulted in the same order. If you're interested, you can carry it out on your own.

    Benchmark code:

    var MAX = 100000, i = 0, 
        a1 = {}, a2 = [], a3 = [],
        value = "";
    
    for ( i=0; i<1024; ++i ) {
        value += "a";
    }
    
    console.time("associative construction");
    for ( i=0; i

    The size and type of value is insignificant to the test as JavaScript uses copy-on-write. A large (1kb) value was used for the purpose of convincing those readers who are not familiar with this feature of JavaScript.

提交回复
热议问题