early return vs single return

Benchmark created by notoriousb1t on


Description

A quick test of the performance of returning early in a method vs storing a returnValue and returning the value at the end of the method

Setup

function earlyReturn(val) {
      if (val === undefined) {
        return 'It is undefined';
      }
      if (val === null) {
        return 'It is null';
      }
      return 'It has something';
    }
    
    function singleReturn(val) {
      var retValue;
      if (val === undefined) {
        retValue = 'It is undefined';
      } else if (val === null) {
        retValue = 'It is null';
      } else {
        retValue = 'It has something';
      }
      return retValue;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
early return
var values = [];
for (var i = 0; i < 50000; i++) {
  values.push(earlyReturn(i % 2 === 0));
}
ready
single return
var values = [];
for (var i = 0; i < 50000; i++) {
  values.push(singleReturn(i % 2 === 0));
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by notoriousb1t on
  • Revision 2: published by notoriousb1t on