JSFiddle - React, Tailwind, and code Playground
by gutek
JavaScript
var ar = createArray(1000000);
function createArray (count) {
var a = [], i;
for(i = 0; i < count; i++) {
a[i] = i;
}
return a;
}
function slow_for (count) {
var i, j;
for(j = 0; j < count; j += 1) {
for(i = 0; i < ar.length; i += 1) {
ar[i];
}
}
}
function slow_for_in (count) {
var i, j;
for(j = 0; j < count; j += 1) {
for(i in ar) {
if (ar.hasOwnProperty(i)) {
ar[i];
}
}
}
}
function slow_for_each (count) {
var i, j;
for(j = 0; j < count; j += 1) {
ar.forEach(function(element, index, arrayi) {
element;
});
}
}
test ('slow for ;;;', slow_for);
test ('slow for in', slow_for_in);
test ('slow for each', slow_for_each);
function test (name, method) {
console.time(name);
method(50);
console.timeEnd(name);
}
test ('fast array access', ok);
// some js engines can optimize slow for ;;;
function ok (count) {
var i, l = ar.length, j;
for(j = 0; j < count; j += 1) {
for(i = 0; i < l; i += 1) {
ar[i];
}
}
}