Wrap around arithmetic vs branches

Benchmark created by amoshydra on


Setup

var tests = [...new Array(1000)].map(function (item, index) { return index });

Test runner

Ready to run.

Testing in
TestOps/sec
Arithmetic
var wrapAround = function wrapAround(inMin, inMax) {
  var valueRange = inMax - inMin;
  return function (inValue) {
    return inMin + ((inValue - inMin) % valueRange + valueRange) % valueRange;
  };
};

var wrap = wrapAround(0, 10);

tests.forEach(function(test) {
  wrap(test);
});
ready
Branching
var wrapAround = function wrapAround(min, max) {
  return function (index) {
    return index < min ? max : index > max - 1 ? min : index;
  };
};

var wrap = wrapAround(0, 10);

tests.forEach(function(test) {
  wrap(test);
});
ready

Revisions

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

  • Revision 1: published by amoshydra on