HTML and CSS Reference
In-Depth Information
conditional with the rest. This is not always a safe choice, because empty strings,
null , 0, and other false values will terminate the loop. Also, this style of looping
performs terribly on some browsers and should be avoided. Because all the tests
access the current item, we can disregard the overhead as fluctuations in the test
results will be the result of the different looping styles. Note that the reversed
while-loop is not directly comparable as it loops the array backwards. However,
whenever order is not important, it's commonly the fastest way to loop an array, as
seen by running the above benchmark.
Benchmarks such as that in Listing 4.6 are dead easy to set up. Still, to make them
easier to integrate into our workflow, we can craft a simple benchmark function
that removes all unnecessary cruft from writing benchmarks. Listing 4.8 shows one
possible such function. The function accepts a label for the series of tests and then
an object where the property names are taken as test names and property values are
run as tests. The last argument is optional and instructs benchmark as to how many
times a test should be run. Results are printed in both full and average time per test.
Listing 4.8 A simple benchmarking tool
var benchmark = (function () {
function init(name) {
var heading = document.createElement("h2");
heading.innerHTML = name;
var ol = document.createElement("ol");
return ol;
function runTests(tests, view, iterations) {
for (var label in tests) {
if (!tests.hasOwnProperty(label) ||
typeof tests[label] != "function") {
(function (name, test) {
setTimeout(function () {
var start = new Date().getTime();
var l = iterations;
while (l--) {
Search WWH ::

Custom Search