My friends and family are under attack in Ukraine.
Donate to protect them directly or help international organizations.

Profiling JS Applications

January 3rd, 2012

Some of the web apps that we build at FooLab rely heavily on Javascript. But when your CPU usage is through the roof, where do you start looking?

Many developers start straight with a hypothesis and then try various corrections until something happens. This is a waste of time; no amount of experience changes that. Follow the scientific method.

1. Ask a question

"Why is my machine using so much CPU?"

2. Observe

I use Chrome Developer Tools to poke around at first. Under the profiles tab, I start recording, perform the actions that seem to be causing the problem a few times and press stop. I remember seeing similar tools in Firefox and Safari.

There are many ways to analyze the data, but I found that sorting by Total to be most helpful. The Total is the time spent in the function and all functions called from within it, giving you the scope to look in.

3. Propose an explanation

Concentrate on functions that you wrote yourself, and then see in your code what they do. Try to think of any processes can be slow, unneeded or executed more times than needed.

4. Benchmark

I use benchmark.js which I include this file in my page. Then I add the necessary code to run the functions spotted in step 2. I like to run this code right after my home-brewed MVC has done initializing:

var suite = new Benchmark.Suite;
suite.add('addEventListeners', function() {
  addEventListeners();
}).add('render', function() {
  render();
}).on('cycle', function(ev, bench) {
  console.log(String(bench));
}).run({
  'async': false,
  'minSamples': 50
});

This will output a line for every .add you have, telling you the number of operations per second and margin of error. Rerun it if the margin is too wide. Make sure that you benchmark as many functions as you can before you start patching it. Write them in a table so that you can later compare with the improved code.

5. Fix the code

Now go ahead and start making adjustments. It's good to make one type of optimization at once and run the benchmark again, writing all the numbers in a table side by side. Example: optimize jQuery selectors first. This way you can see which functions have been improved how, leading you to avoid certain mistakes in the future and having something to demonstrate and teach to your teammates.

Read my next article about some of the common places where jQuery murders your CPU.

Previous: Symfony Form: Extract Values Next: jQuery Performance Pitfalls