var number = Math.random() * 1000;
var min = Math.random() * 300;
var max = Math.random() * 1200;
function ternaryClamp(number, min, max) {
return number > max ? max : (number < min ? min : number);
}
function ternaryMin(number, min) {
return number < min ? number: min;
}
function ternaryMax(number, max) {
return number > max ? number: max;
}
Math.min(Math.max(number, min), max)
Math.min(number, min)
Math.max(number, max)
ternaryClamp(number, min, max);
ternaryMin(number, min)
ternaryMax(number, max)
number > max ? max : (number < min ? min : number)
number < min ? number: min
number > max ? number: max
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Math.min/max | |
Math.min | |
Math.max | |
Ternary clamp | |
Ternary min | |
Ternary max | |
Ternary clamp inlined | |
Ternary min inlined | |
Ternary max inlined |
Test name | Executions per second |
---|---|
Math.min/max | 14949082.0 Ops/sec |
Math.min | 20418864.0 Ops/sec |
Math.max | 19264802.0 Ops/sec |
Ternary clamp | 17589622.0 Ops/sec |
Ternary min | 18996174.0 Ops/sec |
Ternary max | 21272432.0 Ops/sec |
Ternary clamp inlined | 17180900.0 Ops/sec |
Ternary min inlined | 19431834.0 Ops/sec |
Ternary max inlined | 20903712.0 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Definition:
The benchmark is comparing different ways to clamp numbers within a specified range using JavaScript.
Options Being Compared:
Math.max
and Math.min
functions.ternaryClamp(number, min, max)
: Returns the minimum of the number and the maximum value if it's outside the range.ternaryMin(number, min)
: Returns the smaller of the two values (number and minimum).ternaryMax(number, max)
: Returns the larger of the two values (number and maximum).number > max ? max : (number < min ? min : number)
number < min ? number: min
number > max ? number: max
Pros and Cons of Each Approach:
Library Used:
None explicitly mentioned in the benchmark definition. However, the Math.max
and Math.min
functions are part of the JavaScript standard library.
Special JS Features or Syntax:
Not explicitly used in this benchmark. The focus is on comparing different coding approaches rather than showcasing specific features.
Other Considerations:
Alternative Approaches:
Other ways to clamp numbers within a range might include:
number & 0xFF
to get the last byte of an integer)Math.floor((number + max) / step) * step
)However, these alternatives are not being tested in this specific benchmark.