The document discusses various patterns and techniques for improving JavaScript performance, including:
1. Loading scripts asynchronously and deferring execution to improve perceived page load times.
2. Using local variables instead of globals to reduce scope chain lookups and improve minification.
3. Caching expensive operations through memoization and reusing initialization code to avoid redundant work.
4. Avoiding direct DOM access in loops to reduce reflows and repaints, such as building up a string instead of multiple innerHTML assignments.
8. += or array.join()
var res = '', var res = [],
count = 10000; count = 10000;
while (count--) { while (count--) {
res += 'a'; res.push('a');
} }
res = res.join('');
http://jsperf.com/join-concat/
9. “The Pen is mightier
than the Sword” *
* only if the Sword is very small
and the Pen very sharp
15. When benchmarking…
1. Long enough operations
(much longer than 15ms)
2. 200 runs for statistical
significance
3. Filtering outliers
4. 0-timeout end time
40. <!doctype html>
<html>
<head><title>My App</title></head>
<body>
<div id="header">
<img src="logo.png" />
...
</div> <!-- end of chunk #1 -->
... The full body of the page ...
<!-- end of chunk #2 -->
<script src="all_20100925.js"></script>
</body>
</html> <!-- end of chunk #3 -->
70. DOM – case A
// bad
var count = 0;
for (; count < 15000; count += 1) {
document.getElementById('here').innerHTML += 'a';
}
// DOM access = (1 get + 1 set) * 15000
71. DOM – case B
// better
var count = 0, content = '';
for (; count < 15000; count += 1) {
content += 'a';
}
document.getElementById('here').innerHTML += content;
// DOM access: get + set
72. IE 6
IE 7
IE 8
Firefox 3
Firefox 3.5
Safari 3.2
Safari 4
Chrome 2
Chrome 3
Opera 9.64
How bad is A compared to B?
Opera 10