Do loops check the array.length every time when comparing i against array.length?

前端 未结 5 1557
一向
一向 2020-11-30 07:44

I was browsing around and I found this:

var i, len;
for(i = 0, len = array.length; i < len; i++) {  
   //...
}

My first thoughts are:

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 07:58

    Is it worth it? (obviously yes, why else he will do it this way?)

    Absolutely yes. Because, as you say, loop will calculate array length each time. So this will cause an enormous overhead. Run the following code snippets in your firebug or chrome dev tool vs.

    // create an array with 50.000 items
    (function(){
        window.items = [];
        for (var i = 0; i < 50000; i++) {
            items.push(i);
        }
    })();
    
    // a profiler function that will return given function's execution time in milliseconds
    var getExecutionTime = function(fn) {
        var start = new Date().getTime();
        fn();
        var end = new Date().getTime();
        console.log(end - start);
    }
    
    var optimized = function() {
        var newItems = [];
        for (var i = 0, len = items.length; i < len; i++) {
            newItems.push(items[i]);
        }
    };
    
    
    var unOptimized = function() {
        var newItems= [];
        for (var i = 0; i < items.length; i++) {
            newItems.push(items[i]);
        }
    };
    
    getExecutionTime(optimized);
    getExecutionTime(unOptimized);
    

    Here is the approximate results in various browsers

    Browser    optimized    unOptimized
    Firefox    14           26
    Chrome     15           32
    IE9        22           40
    IE8        82           157
    IE7        76           148 
    

    So consider it again, and use optimized way :)
    Note: I tried to work this code on jsPerf but I couldn't access jsPerf now. I guess, it is down when I tried.

提交回复
热议问题