Optimize your JavaScript code with Performance.now ()

By | September 14, 2015

When you want to test the time taken by a function to run in JavaScript, you have the perfect tool for this: Performance.now (). Unlike Date.now() function calculated in relation to the system time, Performance.now() is incremented in a constant manner. Let’s take an example :

function testIncrementString() {
    var str = "0";
    for ( var i = 0; i <= 1000000; i++) {
        str++;
    }
}

function testIncrementNumber() {
    var nbr = 0;
    for ( var i = 0; i <= 1000000; i++) {
        nbr++;
    }
}

These two functions perform the same treatment, incrementing a number. The first increments a number defined as a String while the second increments an Integer. Here is the test performed:

var start = performance.now();
testIncrementString();
var end = performance.now();
console.log('Execution time of the method testIncrementString : '+ (end - start));

start = performance.now();
testIncrementNumber();
end = performance.now();
console.log('Execution time of the method testIncrementNumber : '+ (end - start));

Et voici les résultats obtenus :

Execution time of the method testIncrementString : 12.192525000000003 
Execution time of the method testIncrementNumber : 0.7343619999999902 

This test is simple but lets see how to use the performance.now () method. The same test would be possible with Date.now() but changing the system time would lead to an incorrect result (hour’s Change, Changing NTP). In the case of our test which lasts 12 seconds, this is very unlikely to happen. In the case of a test that takes place over several hours or even days, this may quickly distort the results. Another advantage of performance.now() method is the accuracy of the result. Millisecond against microsecond.

Can i use

Can i Use   tells us that the support is not perfect yet. OperaMini and mobile Safari does not yet support it. Otherwise, you can use it without any problems.

See you soon.

00

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.