4

I have two functions; one is async (testAsync) and one is sync (testSync). I'm trying to use them with benchmark.js. Which one is faster and by how much. They should both throw an error.

I'm confused how I'm supposed to a) setup an asynchronous test b) make sure the test accounts throw an error for each function.

Here's what I got:

import Benchmark from 'benchmark'
var suite = new Benchmark.Suite;

// add tests
suite.add('query validation test sync', function(deferred) {
  try {
    testSync({'name': 'reggi'});
  } catch (e) {
    deferred.resolve();
  }
})
.add('query validation test async', function(deferred) {
  testAsync({'name': 'reggi'}, {})
    .then(deferred.resolve)
    .catch(deferred.resolve);
})
// add listeners
.on('cycle', function(event) {
  console.log(String(event.target));
})
.on('error', function(event) {
  console.log(String(event.target));
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });
alexmac
  • 19,087
  • 7
  • 58
  • 69
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

1 Answers1

1

You should specify defer: true as option the test function:

suite.add('query validation test sync', function() {
  try {
    testSync({'name': 'reggi'});
  } catch (e) {
    // it's sync code, you don't need use defer here
  }
})
.add('query validation test async', {
  defer: true,
  fn: function(deferred) {
    testAsync({'name': 'reggi'}, {})
      .then(deferred.resolve)
      .catch(deferred.resolve);
  }
})
...

Check example on the benchmark.js site (in the middle of section)

alexmac
  • 19,087
  • 7
  • 58
  • 69