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 | var myArray = ['Dog', 'Cat', 'Bird', 'Snake', 'Fish']; |
Vs.
1 | var myArray = ['Dog', 'Cat', 'Bird', 'Snake', '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 | console.time('array slice'); |
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 more realistic example of the performance measurements we might expect in the wild.
Inspired by a post found here