Javascript clamp

Benchmark created by Sam Beckham on


Test runner

Ready to run.

Testing in
TestOps/sec
If statements
function clamp(num, min, max) {
  if (num < min) {
    num = min;
  } else if (num > max) {
    num = max;
  }
  return num;
}

clamp(10, 0, 100); // inside
clamp(100, 0, 10); // too high
clamp(1, 10, 100); // too low
ready
Math functions
function clamp(num, min, max) {
  return Math.max(min, Math.min(num, max));
}

clamp(10, 0, 100); // inside
clamp(100, 0, 10); // too high
clamp(1, 10, 100); // too low
ready
Early returns
function clamp(num, min, max) {
  if (num < min) {
    return min;
  } else if (num > max) {
    return max;
  }
  return num;
}

clamp(10, 0, 100); // inside
clamp(100, 0, 10); // too high
clamp(1, 10, 100); // too low
ready
function clamp(num, min, max) {
  return Math.min(Math.max(num, min), max);
}

clamp(10, 0, 100); // inside
clamp(100, 0, 10); // too high
clamp(1, 10, 100); // too low
ready

Revisions

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

  • Revision 1: published by Sam Beckham on