Talk given at http://jsconf.eu 2009.
You serve up your code gzipped. Your caches are properly configured. Your data (and scripts) are loaded on-demand. That's awesome—so don't stop there. Runtime is another source of slowdowns, and you can learn to conquer those, too.
Learn how to benchmark your code to isolate performance issues, and what to do when you find them. The techniques you'll learn range from the normal (function inlining) to the extreme (unrolling loops).
11. function methodCall(){
function square(n){ return n*n };
var i=10000, sum = 0;
while(i-‐-‐) sum += square(i);
}
function inlinedMethod(){
var i=10000, sum = 0;
while(i-‐-‐) sum += i*i;
}
12. function methodCall(){
function square(n){ return n*n };
var i=10000, sum = 0;
while(i-‐-‐) sum += square(i);
}
function inlinedMethod(){
var i=10000, sum = 0;
while(i-‐-‐) sum += i*i;
}
13. function methodCall(){
function square(n){ return n*n };
var i=10000, sum = 0;
while(i-‐-‐) sum += square(i);
}
function inlinedMethod(){
var i=10000, sum = 0;
while(i-‐-‐) sum += i*i;
}
29. 1 * string coerces the
string into a float,
result = 12.5
double bitwise NOT*
floors the number
> ~~(1 * "12.5")
12
*good overview on http://tr.im/bitwise
37. var test = '';
for (var i = 0;i<10000;i++)
test = test + str;
var test = '', i = 10000;
while(i-‐-‐) test = test + str;
38. for loop while loop
0.12s 0.12s
0.13s 0.13s
0.6s 0.6s
0.04s 0.04s
39. for loop while loop
0.12s 0.12s
0.13s 0.13s
0.6s 0.6s
0.04s 0.04s
40. for loop while loop
0.12s 0.12s
0.13s 0.13s
0.6s 0.6s
0.04s 0.04s
41. for loop while loop
0.12s 0.12s
0.13s 0.13s
0.6s 0.6s
0.04s 0.04s
42. for loop while loop
0.12s 0.12s
0.13s 0.13s
0.6s 0.6s
0.04s 0.04s
43. var test = '';
for (var i = 0;i<10000;i++)
test = test + str;
var test = '', i = 10000;
while(i-‐-‐) test = test + str;
3 expressions in “for”
1 expression in “while”
(when i equals 0, expression will be false)
52. function uncached(){
var i = 10000;
while(i-‐-‐) window.test = 'test';
}
function cached(){
var w = window, i = 10000;
while(i-‐-‐) w.test = 'test';
}
68. >>> var n = 1;
undefined
>>> if(true && (n=2)) ...;
>>> n
2
>>> if(true || (n=3)) ...;
>>> n
2
not a pure engine optimization,
the execution actually stops
here, n=2 needs to
be evaluated,
so n is set to 2
here it doesn’t
(expression must
be true), so n is
NOT set to 3