9 useful techniques to optimize your Javascript

Javascript is an infamously easy language to program in. However, just because something works doesn’t mean you’re doing it right. Oftentimes, programmers will write a script to provide functionality they need and then leave it as soon as it’s working. Don’t be like those guys: read this tutorial on Javascript optimization (or at least skim it!) and apply the techniques listed here in your code. Your users will thank you.

1) Use object literals

Use object literals wherever you can instead of manually writing out the object declaration like this: var myObj = new Object();

What you should not do:

[gist]https://gist.github.com/2580182[/gist]

What you should do:

[gist]https://gist.github.com/2580266[/gist]

2) Use array literals

This is another important optimization/code improvement you can make: avoid typing out your array declarations like this: var myArray = new Array();

What you should not do:

[gist]https://gist.github.com/2630289[/gist]

What you should do:

[gist]https://gist.github.com/2630300[/gist]

3) A faster for-loop

If you’re iterating over an array, you typically do something like for(var i = 0; i<myArr.length; i++). While this is correct, there are a few optimizations that can be made. Observe:

Storing the length variable

You can store the length of the array in your for loop if you’re not planning on changing the array in your loop. This way, you won’t have to compute the length of the array each iteration of the for-loop. It looks like this:

[gist]https://gist.github.com/2630454[/gist]

The gain here isn’t much, but is an optimization that can be made.

Using a reverse while loop

If you’re really concerned about speed and code optimization, you can use a reverse while loop, as it’s the fastest of the family of for loops. The reverse while loop looks like this:

[gist]https://gist.github.com/2630484[/gist]

This works because we’re subtracting from a variable that (should be) greater than 1 until the while loop hits 0–in which case, it stops. Why? Because in Javascipt, while loops iterate until their condition evaluates to a “falsy” value (e.g. a value that evaluates to false–an empty string, 0, false, etc.). In our case, the falsy value is 0.

4) Using Array.join instead of concatenating

Another small optimization (that used to be a rather big optimization before the + operator was fixed) is to use Array.join instead of concatenating strings.

What’s slower:

[gist]https://gist.github.com/2630555[/gist]

What’s (somewhat) faster:

[gist]https://gist.github.com/2639177[/gist]

5) A shorter (and faster) if statement

Your typical if statement looks something like if(condition){…} and is pretty much what you want to be doing 99% of the time. However, there is another if statement that often goes unnoticed. It looks like this:

condition && (statement);

Where condition is the condition you want evaluated and statement is the code you want executed. Note the parentheses; these are essential or the if statement will not be executed (and will in fact throw an error). You can also use multiple conditions as well, just as you would in a standard if statement. A short if statement with multiple conditions would look like this:

condition && condition && (statement);

Notes:

  1. When used, this method should have a comment explanation to avoid obfuscating your code.
  2. Although this method is marginally faster than the standard if statement, don’t expect it to improve your code’s performance by much.
  3. This method will throw an error in jsLint and code validators of the like as it’s really an “abusage” of the Javascript language as opposed to a “good practice”.

6) Using the ternary operator

There are two ways of declaring an if/else statement– the standard way and the more uncommon way that uses a ternary operator. While the difference in speed between the two conditional constructs is negligible, the ternary operator is often shorter than the standard if/else statement, although sometimes less readable. Let’s take a look at the format of a ternary operator:

(condition) ? case true : case false;

As you can see, the ternary operator is optimal for short operations with little logic.

When to use the ternary operator:

When the logic you’re using is simple enough to fit on one line, then you can use the ternary operator. If, on the other hand, you think your condition or statement(s) will be too long to fit on one line (or you have nested if/else statements), you probably shouldn’t be using the ternary operator.

7) Avoid unnecessary DOM manipulation

This is a biggie–be careful about how often you manipulate the DOM. If you can find a way to batch DOM manipulation calls, then do so. For instance, observe the following code:

This is really bad code:

[gist]https://gist.github.com/2639505[/gist]

This code is a lot better:

[gist]https://gist.github.com/2639515[/gist]

Now, in the second code snippet, we only talk to the DOM twice, instead of the ten times we talked to it in the first code snippet. This is great! Now, let’s combine this with some other optimization techniques mentioned earlier in the article to get a really nice bit of code.

This code is really good:

[gist]https://gist.github.com/2639544[/gist]

I’ll leave it as an exercise to the reader to figure out why this is the best method to manipulate a DOM element’s innerHTML value. Leave your explanation in the comments!

8) Avoid unnecessary variables

This is a questionable optimization. Although avoiding necessary variables can indeed speed up your code, you have to be careful about exactly how many variables you cut out. Often, cutting out too many variables can result in you unintentionally obfuscating your code. Nonetheless, there are many times when an extra variable need not be initialized.

When you’ve finished writing a particular chunk of code, look over it and scan for unnecessary variables; if you find one that you can cut out without harming the readability of your code (too much), then do so.

9) Always, always, always reread your code!

This is the most important optimization of all–when you’ve finished writing a piece of code, don’t just leave it. Go back and read it over once, twice, even three times. Often, you’ll notice little things here and there that could be improved upon and sometimes, you’ll find a chunk of code that leaves you wondering how you possibly could have written it. Fixing these small (and sometimes not so small!) logic errors is usually the best method you can find to improve your code.

Just remember, kids: readability > speed

Just because you see a way to optimize something doesn’t mean you should. A lot of the time, readability is more important than code optimization–while your users may appreciate the increased performance you get out of your optimized code, your fellow maintainers (and maybe even you in three months, or a year, or whatever) will not.

Leave a Reply

Your email address will not be published. Required fields are marked *