HTML and CSS Reference
In-Depth Information
var total = new Date().getTime() - start;
var li = document.createElement("li");
li.innerHTML = name + ": " + total +
"ms (total),"+(total / iterations) +
"ms (avg)";
view.appendChild(li);
}, 15);
}(label, tests[label]));
}
}
function benchmark(name, tests, iterations) {
iterations = iterations
||
1000;
var view = init(name);
runTests(tests, view, iterations);
}
return benchmark;
}());
The benchmark function does one thing noticeably different from our previ-
ous example. It runs each iteration as a function. The test is captured as a function,
which is run the specified number of times. This function call itself has a footprint,
so the end result is less accurate as to how long the test took, especially for small
test functions. However, in most cases the overhead is ignorable because we are
testing relative performance. To avoid having the function call skew tests too much,
we can write the tests so that they are sufficiently complex. An alternative way to
implement this is to take advantage of the fact that functions have a length prop-
erty that reveals how many formal parameters a function takes. If this number is
zero, then we loop. Otherwise, we will assume that the test expects the number of
iterations as an argument and simply call the function, passing the iteration count.
This can be seen in Listing 4.9.
Listing 4.9 Using Function.prototype.length to loop or not
// Inside runTests
(function (name, test) {
setTimeout(function () {
var start = new Date().getTime();
var l = iterations;
if (!test.length) {
while (l--) {
 
Search WWH ::




Custom Search