HTML and CSS Reference
In-Depth Information
// Run tests
runBenchmark("for-loop",
forLoop);
runBenchmark("for-loop, cached length",
forLoopCachedLength);
runBenchmark("for-loop, direct array access",
forLoopDirectAccess);
runBenchmark("while-loop",
whileLoop);
runBenchmark("while-loop, cached length property",
whileLoopCachedLength);
runBenchmark("reversed while-loop",
reversedWhileLoop);
runBenchmark("double reversed while-loop",
doubleReversedWhileLoop);
The setTimeout call is important to avoid choking the browser while testing.
The browser uses a single thread to run JavaScript, fire events and render web pages,
and the timers allow the browser some “breathing room” to pick up on queued tasks
between tests that are potentially long running. Breaking the workload up with
timers also avoids browsers interrupting the tests to warn us about “slow scripts.”
To run these benchmarks, all we need is a simple HTML file, like the one in
Listing 4.7, that loads the script. Save the file in benchmarks/loops.html .
Listing 4.7 YUI Test HTML fixture file
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Relative performance of loops</title>
<meta http-equiv="content-type"
content="text/html; charset=UTF-8">
</head>
<body>
<h1>Relative performance of loops</h1>
<script type="text/javascript" src="../lib/benchmark.js">
</script>
<script type="text/javascript" src="loops.js"></script>
</body>
</html>
All the tests do the exact same thing: loop over all items in the array and access
the current item. Accessing the current item adds to the footprint of the test, but
it also allows us to compare the loop that accesses the current item in the loop
 
Search WWH ::




Custom Search