原文地址:http://www.jayway.com/2011/03/28/high-performance-javascript/javascript
Load the Javascript files right before the end body tag, this will allow the
page to render without having to wait for all the Javascript files.html
With normal loading, the files are loaded sequentially. Each file will
be loaded and parsed before the next file starts to load. Merge them
together into one large file. While you are at it, you should also
minimize it. Tools to help you with this are:java
YUI Compressornode
If normal loading with grouped files is not good enough, it is also
possible to load the files asynchronously. This will also allow you to
load files on demand. Tools for this are:web
HeadJSajax
Literal values and local variables can be accessed very quickly. Array
access and member access take longer. If the prototype chain or scope
chain needs to be traversed, it will take longer the further up the chain
the access is. Global variables are always the slowest to access because
they are always last in the scope chain.express
You can improve the performance of JavaScript code by storing frequently
used, object members, array items, and out-of-scope variables, in local
variables.api
All DOM manipulation is slow.app
// Create a document fragment var fragment = document.createDocumentFragment(); // Do something with framgment // Append the fragments children to the DOM document.getElementById('mylist').appendChild(fragment);
// Clone Node var old = document.getElementById('mylist'); var clone = old.cloneNode(true); // Do something with clone // Replace node with clone old.parentNode.replaceChild(clone, old);
Use algortithms with better complexity performance for large collections.less
Strings concatenation is quite fast in most browsers. In IE, you may
need to use Array.join.
Regular expression can be improved by:
The total amount of time that a single JavaScript operation should take
is 100. If it takes longer it needs to be split up, this can be done
using timers.
Two determining factors for whether a loop can be done asynchronously
using timers:
// Function for processing an array in parallel function processArray(items, process, callback) { var minTimeToStart = 25; var copyOfItems = items.concat(); setTimeout(function() { process(copyOfItems.shift()); if (copyOfItems.length > 0) setTimeout(arguments.callee, minTimeToStart); else callback(items); }, minTimeToStart); } // Function for processing multiple tasks in parallel function processTasks(tasks, args, callback) { var minTimeToStart = 25; var copyOfTasks = steps.concat(); setTimeout(function() { var task = copyOfTasks.shift(); task.apply(null, args || []); if (copyOfTasks.length > 0) setTimeout(arguments.callee, minTimeToStart); else callback(); }, minTimeToStart); }
You should limit the number of high-frequency repeating timers in your
web application. It is better to create a single repeating timer that
performs multiple operations with each execution.
It is not recommended to have minTimeToStart less than 25
milliseconds, because there is a risk that the timers will fill up the
queue.
// Timed version of process array, where each version is able to // process items from the array for up to 50 milliseconds. function timedProcessArray(items, process, callback) { var minTimeToStart = 25; var copyOfItems = items.concat(); setTimeout(function() { // (+) converts the Date object into a numeric representation var start = +new Date(); do { process(copyOfItems.shift()); } while (copyOfItems.length > 0 && (+new Date() - start < 50)); if (copyOfItems.length > 0) setTimeout(arguments.callee, minTimeToStart); else callback(items) }, minTimeToStart); }
Newer browsers support web workers. Web workers does not run in the
UI-thread and does not affect responsiveness at all. Their environment
is limited to allow this to work. It is limited to:
// Application code var worker = new Worker("code.js"); worker.onmessage = function(event) { alert(event.data); }; worker.postMessage("Tapir"); // Worker code (code.js) //inside code.js importScripts("file1.js", "file2.js"); // importing some files self.onmessage = function(event) { self.postMessage("Hello, " + event.data + "!"); };
Any code that takes longer than 100 milliseconds to run should be
refactored to use webworkers to decrease the load on the UI-thread.
Favor lightweight formats in general; the best is JSON and
a character-delimited custom format. If the data set is large and parse
time becomes an issue, use one of these two techniques:
JSON-P data, fetched using dynamic script tag insertion. This treats the
data as executable JavaScript, not a string, and allows for extremely
fast parsing. This can be used across domains, but shouldn’t be used
with sensitive data.
A character-delimited custom format, fetched using either XHR or dynamic
script tag insertion and parsed using split(). This technique parses
extremely large datasets slightly faster than the JSON-P technique, and
generally has a smaller file size.
XML has no place in high-performance Ajax.
Cache data! The fastest Ajax request is one that you don’t have to make.
There are two main ways of preventing an unnecessary request:
Some more guidelines that will help your Ajax appear to be faster:
Know when to use a robust Ajax library and when to write your own
low-level Ajax code.
Native methods are always faster than anything you can write in
JavaScript.
The build and deployment process can have a tremendous impact on the
performance of a JavaScript-based application. The most important steps
in this process are:
All these steps should be automated using build tools
YUI Compressor
dynaTrace Ajax Edition
Chrome Developer Tools
Charles Proxy