Recently, I was assigned a work to optimize java-script code for performance. I was very excited about this, after few hour of work…. it turned into my nightmare. You must be laughing but believe me most of JavaScript code were “If, else if and loop” and it was making me as if I am looking into galaxy of code trying to find some fading starts. Eventually after giving some serious thought I realized, if you are using some JavaScript framework in your application (code was based on prototype.js) only things that you can optimize are “if, else if and looping”. May be you won’t agree with me, but code I was optimizing was like that only. So I knew where I have to optimize the code.
I started with “for” loop. Below I am putting a snippet of most general declaration of “for loop statement”
It is very interesting to know that java-script “for statement” evaluates “condition” and “increment” for every increment. For example if I am executing a loop for (var i=0;i<5;i++), both parts will execute 5 times.
To justify this, I made a very simple program that will demonstrate this fact:
You can also see this JSFiddle.
Ok, so far so good. Now at least I knew how I can optimize for loops. Soon I encounter few “for in” loop over array. I was sure that “for in” is better than “for loop” (without knowing the actual facts), but since my area of code optimization was very limited (if, else if and loop), I thought of “googling” about this. After reading few initial results I was feeling like a small kids who’s just caught red handed by mom. No…..:-(. I was wrong “for in” is not cost effective over array. Rather it involves more processing overhead. For array “for” loop is a better choice. Just to establish the fact, I made an array of 10000 elements and lopped using “for..in” as well as “for”…. And the results are….. 3.5 ms and 0.04 ms respectively.
You can also see this JSFiddle.
OMG, I optimized most of the code. “IF” statements are looking good what should I optimize here….. But once bitten twice shy…. Remember “for in” case above. Below are my finding over “If” statement:
1, Most general “If” statement would look something like this:
2, Always compare with “===” in place of “==”
3, In “Java-Script”, you can do this in one line like this:
4, Evaluate Boolean variable directly
5, Evaluate simple and light condition first
Finally I made the code optimization and tried putting my experience here. Hope it’s helpful.
See you soon.