---
title: Quick Performance Testing using Node
description: test
date: 2017-07-03
tags: 'Performance'
source: https://brianchildress.co/blog/quick-performance-testing-using-node
---

# Quick Performance Testing using Node

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
```js
var myArray = ['Dog', 'Cat', 'Bird', 'Snake', 'Fish'];
console.log(myArray.slice(-1)[0]); // fish
```

##### Vs.

```js
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_)](https://nodejs.org/api/console.html#console_console_time_label) and [console.timeEnd(_label_)](https://nodejs.org/api/console.html#console_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.

```
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 more realistic example of the performance measurements we might expect in the wild.


_Inspired by a post found [here](http://www.codeblocq.com/2016/05/Get-the-last-element-of-an-Array-in-JavaScript/)_
