- Performance .. is not just about how long it takes for the page to load, but also about how it responds as it’s being used.
- Out-of-scope variables take longer to access than local variables.
- A very common mistake that leads to performance issues is to omit the var keyword when assigning a variable’s value for the first time.
- If an array item or object property is used more than once, store it in a local variable to speed up access to the value.
- Generally speaking, interacting with DOM objects is always more expensive than interacting with non-DOM objects.
- The if statement is best used with a small number of discrete values or a range of values; the switch statement is best used when there are between 3 and 10 discrete values to test for; array lookup is most efficient for a larger number of discrete values.
- To make a loop the most efficient, reverse the order in which you process the items so that the control condition compares the iterator to zero.
- Trimming strings may be expensive, depending on the size of the string.
- Steven Levithan's optimized string trimming function:
function trim(text){
text = text.replace(/^\s+/, "");
for (var i = text.length - 1; i >= 0; i--) {
if (/\S/.test(text.charAt(i))) {
text = text.substring(0, i + 1);
break;
}
}
return text;
} - Array processing is one of the most frequent causes of long-running scripts.
- Generally speaking, no single continuous script execution should take longer than 100 milliseconds...
- Because JavaScript is a single-threaded language, only one script can be run at a time per window or tab.
- Exactly what causes the browser to display the long-running script dialog varies depending on the vendor:
- Internet Explorer displays it when 5 million (by default) statements have been executed.
- Firefox shows it when a script takes longer than 10 seconds (default).
- Safari displays it when the execution time exceeds default timeout of five seconds
- Chrome (as of version 1.0) has no set limit on how long JavaScript is allowed to run. The process will crash when it has run out of memory.
- Opera is the only browser that doesn’t protect against long-running scripts. Scripts are allowed to continue until execution is complete
Thursday, 5 April 2012
JavaScript Performance tips
Posted on 19:15 by Unknown
Excerpted from "Chapter 7: Writing Efficient JavaScript" of the book "Even Faster Websites":
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment