Sunday, 9 April 2017

Finding slow JavaScript

Working with Apex I regularly write Javascript. Most of the time these client-side code snippet are blazing fast, but in some cases they take a few seconds to execute.

In these cases I want to see which part of the code is slow. In this process I use two very simple JS functions which make life a lot easier for me:

var timing_start;

function start_timing( text) {
    timing_start = performance.now();
    if ( text) { console.log('Start timing:'+text); } 
}

function show_timing(text)
{ console.log('Timing:'+text+', milliseconds:'+ (performance.now()-timing_start) );  }

You can put this code on the page or include it in a general JS file.

 The use of these functions is really simple:

start_timing();
...
code to be timed 
...
show_timing('Data retrieved');

This will result in the following output in the browser's console:


Timing:Data retrieved, milliseconds:784.2350000000001

The show timing calls display the elapsed time since the last call to start_timing.

Happy JavaScripting

No comments: