The Wayback Machine - https://web.archive.org/web/20120521014858/http://en.wikibooks.org/wiki/JavaScript/Optimization

JavaScript/Optimization

From Wikibooks, open books for an open world
< JavaScript
Jump to: navigation, search
Previous: Namespaces Index Next: Metaprogramming
TODO

Editor's note
The following is only an outline, to be fleshed out.

Contents

[edit] JavaScript Optimization

[edit] Optimization Techniques

  • High Level Optimization
    • Algorithmic Optimization (Mathematical Analysis)
    • Simplification
  • Low Level Optimization
    • Loop Unrolling
    • Strength Reduction
    • Duff's Device
    • Clean Loops
  • External Tools & Libraries for speeding/optimizing/compressing JavaScript code

[edit] Common Mistakes and Misconceptions

[edit] String concatenation

Strings in JavaScript are immutable objects. This means that once you create a string object, to modify it, another string object must theoretically be created.

Now, suppose you want to perform a ROT-13 on all the characters in a long string. Supposing you have a rot13() function, the obvious way to do this might be:

var s1 = "the original string";
var s2 = "";
 
for(i=0; i < s1.length; i++) {
  s2 += rot13(s1.charAt(i));
}

Especially in older browsers like Internet Explorer 6, this will be very slow. This is because, at each iteration, the entire string must be copied before the new letter is appended.

One way to make this script faster might be to create an array of characters, then join it:

var s1 = "the original string";
var a2 = new Array(s1.length);
var s2 = "";
 
for(i=0; i < s1.length; i++) {
  a2[i] = rot13(s1.charAt(i));
}
s2 = a2.join('');

Internet Explorer 6 will run this code faster. However, since the original code is so obvious and easy to write, most modern browsers have improved the handling of such concatenations. On some browsers the original code may be faster than this code.

A second way to improve the speed of this code is to break up the string being written to. For instance, if this is normal text, a space might make a good separator:

var s1 = "the original string";
var c;
var st = "";
var s2 = "";
 
for(i=0; i < s1.length; i++) {
  c = rot13(s1.charAt(i));
  st += c;
  if(c == " ") {
    s2 += st;
    st = "";
  }
}
s2 += st;

This way the bulk of the new string is copied much less often, because individual characters are added to a smaller temporary string.

Previous: Namespaces Index Next: Metaprogramming
Personal tools
Namespaces

Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export
Morty Proxy This is a proxified and sanitized view of the page, visit original site.