Quick Performance Testing using Node

Posted by brian on 07-03-2017
posts

There’s always a debate about which approach to solving a problem will be more performant in your application. Some comparisons are clear, others can be a toss up. Here’s a quick way to setup a performance test using Node.

Finding the last element in an array

1
2
var myArray = ['Dog', 'Cat', 'Bird', 'Snake', 'Fish'];
console.log(myArray.slice(-1)[0]); // fish
Vs.
1
2
var myArray = ['Dog', 'Cat', 'Bird', 'Snake', 'Fish'];
console.log(myArray[myArray.length - 1]); // Fish

To evaluate the performance we can use the console.time(label) and console.timeEnd(label). The label makes the connection between console.time() and console.timeEnd(), Node evaluates the time between the two function calls in a sub-millisecond measurement.

To use this in our ‘find the last element in the array’ example we can setup out performance test like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
console.time('array slice');
for(var i = 0; i < 1000000; i = i + 1) {
var myArray = ['Dog', 'Cat', 'Bird', 'Snake', 'Fish'];
var value = myArray.slice(-1)[0];
}
console.timeEnd('array slice');
console.time('array idx');
for(var i = 0; i < 1000000; i = i + 1) {
var myArray = ['Dog', 'Cat', 'Bird', 'Snake', 'Fish'];
var value = myArray[myArray.length - 1];
}
console.timeEnd('array idx');

// array slice 92.512ms
// array length 4.862ms

In our test the length - 1 approach to finding the last element in the array really beats the slice approach, finishing in a fraction of the time. For testing we using a for loop that increments 1 million times to give a moer realistic example of the performance measurements we might expect in the wild.

Inspired by a post found here