/ JavaScript

29% Slower Code

Recently we had a discussion about some simple JavaScript and the performance of different solutions to the same problem.

The problem and solutions

The problem was:

Write a function to return the smallest value from an Array of Numbers.

One solution was:

function smallest(arr) {
  return Math.min.apply(this, arr);
}

This is a very nice use of Math.min and it’s a simple, short and readable method.

My solution was:

function smallest(arr) {
  for (var i = 0, len = arr.length, num; i < len; i++) {
    if (typeof num === 'undefined' || num > arr[i]) {
      num = arr[i];
    }
  }
  return num;
}

This is good old JavaScript walking through the Array and finding the smallest of the values but it’s a lot more code and it’s not quite as readable.

Both answers solve the problem but we then questioned the performance of each of the answers.

Which is faster?

I created a simple test based on these two solutions (here) to return the smallest and largest value from an Array and we found that one of the answers actually performs up to 29% slower than the other.

Yes; it’s the shorter of the two code snippets.

What that tells us

Yes this simple test is based upon using the Math.min library method instead of simple JavaScript but this is still a relevant test.

We see the use of library methods in favour of plain JavaScript all the time and we rarely think of which one is actually faster until we need to run some performance tests.

It really does show that we all need to be mindful of the consequences of writing shortened code and the potential performance issues of using library methods in favour of plain old JavaScript.

It’s great to reduce your source code line count; but if your application could perform better then it’s certainly worth writing the extra syntax.

Browser differences

We ran the tests through various browsers; in each case the longer of the two code snippets outperformed the smaller and showed up to 29% faster within Google Chrome.

Interestingly; Project Spartan was recognised as ‘Chrome 39.0.2171’ by jsperf and didn’t perform much better than Internet Explorer 11 - though they were both running within VMWare Fusion and also running on the Windows 10 Preview so we can’t take too much away from that just yet.

Paul Massey

Paul Massey

Founded the Genoveus Production Studio in 2003, JavaScript engineer at Scriptwerx, Director and DP at Mediawerx. Passionate about technology, filmmaking, robotics, IoT, photography, music and cars.

Read More