问题
Made an observation - appealing to non-exists element of array, reduces the performance very much. It’s visibly on long loops. Why it happens?
Example:
var filledArray = []; //This array will filled
var emptyArray = []; //This array leave empty
//fill one array
for(var i = 0; i < 1e6; i++) {
filledArray[i] = true;
}
//Just iterate the array and call its elements
//In filled array all elements exists, in empty array non-exists
function callItems(arr) {
for(var i = 0; i < 1e6; i++) {
arr[i];
}
}
//measurement function
function bench(f, d) {
var start = new Date;
f(d);
alert(new Date - start, ' ms');
}
////Result for filled array
//Firefox 24.0: 20 ms
//Chrome 30.0: 3 ms
bench(callItems, filledArray);
////Result for empty array
//Firefox 24.0: 340 ms
//Chrome 30.0: 70 ms
bench(callItems, emptyArray);
Edit:
If you running code in Firefox, note that on result in Firefox influence Firebug – enabled or disabled it. I understood it, after various tests.
If it enabled – results same, how i wrote above. But if Firebug don’t enabled after launch Firefox – time equal 2ms (that faster than Opera and Chrome ) and difference between empty/filled array disappears.
Also affect on results swap calls function bench() – first with empty, then with filled array (only in Firefox with enabled Firebug, without Firebug and in other browsers results unchanged).
Why such affect Firebug? – additional question.
回答1:
This is most likely because the JavaScript engine is allocating the space for elements 0 through i in the empty array. When the array is filled the JS engine simply accesses the element and returns its value. In the empty case the engine prepares for a value to be set in that spot in the array, which requires allocating the space for that element.
Running your sample code in Chrome 30 with the Task Manager open I observed a 10k spike in memory usage by the page during the second step (iterating over the empty array). This space was quickly freed afterwards as the engine realized the space wasn't being used.
来源:https://stackoverflow.com/questions/19554859/appealing-to-non-exists-element-of-array-reduces-the-performance-very-much