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 optimisations considering the speed and efficiency of today’s browsers. Nevertheless for large number of iterations, these optimisations 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'; }
// optimised 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 (switch-case vs if-else) on jsBench across various browsers. This test runs comparison between twenty switch-case and if-else conditions over 100,000 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)1.
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
var a = 0;
for (var i = 0; i < 10000; i++) {
a++;
}
// optimised code
var a = 0;
for (var i = 10000; i; i−−) {
a++;
}
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. See Javascript Looping Performance Test (forward vs backward) on jsBench
- Linear time complexity. See: Big O Notation in Wikipedia ↩︎


Leave a reply to Rahul B. Cancel reply