Optimizing JavaScript (part 1)

In my years of experience in programming, I have observed that certain performance ‘tweaks’ work best for certain languages. This is mostly due to the nature of the interpreter ((Interpreters are programs that execute codes one line at a time. See: Interpreter  in Wikipedia))/compiler ((a program that decodes instructions written in a higher order language. See: Compiler in Wikipedia)) involved in executing a particular piece of code.

With respect to JavaScript, there are quite a few very queer tweaks that can tune up your JavaScript applications even further. These are very minor optimizations considering the speed and efficiency of today’s browsers. Nevertheless for large number of iterations, these optimizations work wonders.

Replace if-else block with switch statements.

One might argue that a block of if-then statements when compared and switch-case statements should not make a difference. However, in my experience, I have observed that for JavaScript, converting a series of if-else block into switch statements give a noticeable performance increase.

// original code
var a = 4, b;
if(a==1) { b = 'a is one'; }
else if(a==2) { b = 'a is two'; }
else if(a==3) { b = 'a is three'; }
else if(a==4) { b = 'a is four'; }
// optimized code
var a = 4, b;
switch(a) {
  case 1: b = 'a is one'; break;
  case 2: b = 'a is two'; break;
  case 3: b = 'a is three'; break;
  case 4: b = 'a is four'; break;
}

You verify the result yourself by running this Javascript Condition Performance Test Script (switch-case vs if-else) across various browsers. This test runs comparison between twenty switch-case and if-else conditions over 100000 iterations.

For very large number of iterations, (say for example a 10,000 iteration of the above code samples,) you will notice that the switch statement has a very predictable temporal complexity of O(n) ((Linear time complexity. See: Big O Notation in Wikipedia)).

Also, (again due to the nature of the compiler/interpreter,) a switch-case structure with case variables increasing predictably and sequentially, is faster than a switch-case statement with random case comparison.

Count loops backwards to zero

This might appear to be the most unbelievable, but it is true. Counting a loop backwards in JavaScript improves performance! Instead of starting from zero, if we from a large number and compare it back to zero, we would get a better performance.

// original code to run 10000 iterations
for(var i = 0; i < 10000; i++) {
  // loop body
}
// optimized code
for(var i = 10000; i; i−−) {
  // loop body
}

By design, most compilers are fast while comparing with “zero”. Hence, not only counting backwards, but also making sure that the comparison takes place with respect to zero would add to the efficiency of looping.

7 Replies to “Optimizing JavaScript (part 1)”

  1. Damn! I could never believe that counting down in a loop works… and guess what you actually made me write a test code to try it out.

    It worked in FF and Chrome but very little difference in IE. Even then… it works.

  2. Oops! Typo there! i- should be i−−! (You see, Windows Live Writer automatically converted — to a longer dash!)
    My statement :
    for(var i = 10000; i; i−−)
    is equivalent to
    for(var i = 10000; i==0; i−−)

  3. One way how you can check your execution time on javascript is using date tag, see the example below:

    <script type="text/javascript">
    function check_processing_time(){
      var start_time,end_time;
        start_time = new Date().getTime();
        FunctionName();
        end_time=new Date().getTime();
    alert('Elapsed time: '+((endTime-startTime)/1000)+' seconds.');
    }
    </script>
  4. Well… I think that using a language profiler to track execution times is another alternative. For JavaScript, a good profiler is FireBug. Other than that, there is JS Profiler 2.o.

    Using a profiler is a more robust and technically sound way to track memory leak and performance of your applications. I will soon write a section enunciating the benefits of using a profiler.

  5. In your “if, else if” block, you compare the value with operator == which converts type of data. Lots of web sites advise the use of ===.
    I think a switch statement is performing a comparison same way than ==. So are you sure it would be quicker than the “if, else is” block with operator === ?
    For a great benchmark on the loops performance, there is :
    http://blogs.sun.com/greimer/entry/best_way_to_code_a
    which shows how bad is the “for (var i in array)” !!

    1. “===” may not be a desirable operator for every situation. In case of switch statement, the switching variable is compared for existence only once. Whereas, in case of if-else block, both sides of the “==” operator is checked for existence and that, to some extent, adds up to the execution time.

      Now, with an if-else block with “===” operator, the above logic theoretically appears to have been overcome. But, apparently it is not! I did run a test of 100000 iterations with 20 cases and if-else per loop and the result still shows that switch-case is faster and that “==” or “===” has almost no difference in execution time. (View Testing Script)

      And ah! The link you mentioned is really worthwhile. It really has some extensive validation of the above points. 🙂

Leave a Reply