HTML and CSS Reference
In-Depth Information
Windows Vista complicates the matter by providing browsers with timers that only
update every 15ms. This means that fast-running tests can be hugely inaccurate, the
best approach is to run tests for at least 500ms or so.
Listing 4.5 shows a function that we will use to run some benchmarks to measure
relative performance. Save it in lib/benchmark.js .
Listing 4.5 A benchmark runner
var ol;
function runBenchmark(name, test) {
if (!ol) {
ol = document.createElement("ol");
document.body.appendChild(ol);
}
setTimeout(function () {
var start = new Date().getTime();
test();
var total = new Date().getTime() - start;
var li = document.createElement("li");
li.innerHTML = name + ": " + total + "ms";
ol.appendChild(li);
}, 15);
}
Listing 4.6 uses this function to measure relative performance of different loop-
ing styles. Save the file in benchmarks/loops.js .
Listing 4.6 Benchmarking loops
var loopLength = 500000;
// Populate an array to loop
var array = [];
for(vari=0;i<loopLength; i++) {
array[i] = "item" + i;
}
function forLoop() {
for (var i = 0, item; i < array.length; i++) {
item = array[i];
}
}
 
Search WWH ::




Custom Search