freeCodeCamp Challenge Guide: Return Largest Numbers in Arrays

Benchmark by @P1xt
Results … ES6 and “Function.apply.bind” may look all snazzy and smart but neither is the actual advanced solution. Because, an advanced solution takes efficiency into account and the “vanilla” solution is by far the fastest / most efficient of the three.

  1 var Benchmark = require('benchmark');
  2 var suite = new Benchmark.Suite;
  3
  4 function largestOfFourBind(arr) {
  5   return arr.map(Function.apply.bind(Math.max, null));
  6 }
  7
  8 function largestOfFourES6(arr) {
  9   return arr.map((a) => Math.max(...a));
 10 }
 11
 12 function largestOfFourVanilla(arr) {
 13   return arr.map(function(a) {
 14     return Math.max.apply(null, a);
 15   });
 16 }
 17
 18 // add tests
 19 suite.add('bind', function() {
 20     largestOfFourBind([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [10    00, 1001, 857, 1]]);
 21 })
 22 .add('es6', function() {
 23     largestOfFourES6([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [100    0, 1001, 857, 1]]);
 24 })
 25 .add('vanilla', function() {
 26     largestOfFourVanilla([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39],     [1000, 1001, 857, 1]]);
 27 })
 28 // add listeners
 29 .on('cycle', function(event) {
 30    console.log(String(event.target));
 31 })
 32 .on('complete', function() {
 33    console.log('Fastest is ' + this.filter('fastest').map('name'));
 34 })
 35 // run async
 36 .run({ 'async': true });

output:

bind x 355,997 ops/sec ±4.59% (71 runs sampled)
es6 x 91,822 ops/sec ±1.26% (75 runs sampled)
vanilla x 802,980 ops/sec ±1.60% (76 runs sampled)
Fastest is vanilla

EDIT

As a thought experiment I went back and tested the beginner and intermediate solutions against the other three.

The beginner solution was actually the fastest far and away by a LARGE margin.

beginner x 3,482,777 ops/sec ±1.66% (69 runs sampled)
intermediate x 497,563 ops/sec ±1.83% (71 runs sampled)
bind x 378,711 ops/sec ±1.62% (74 runs sampled)
es6 x 95,515 ops/sec ±1.03% (84 runs sampled)
vanilla x 815,023 ops/sec ±0.97% (81 runs sampled)
Fastest is beginner

This was an important lesson, to me at least, that the solution that uses the least characters, or that uses the most advanced features of the language, isn’t necessarily the most advanced solution if the beginner solution is more efficient.

59 Likes