const a = 5
const b = 2
const max = (a, b) => {
if (a > b) {
return a
}
return b
}
max(a, b)
const a = 5
const b = 2
const max = (a, b) => a > b ? a : b
max(a, b)
const a = 5
const b = 2
const max = (a, b) => a * (a > b) + b * (b > a)
max(a, b)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
branched | |
ternary | |
math |
Test name | Executions per second |
---|---|
branched | 868210176.0 Ops/sec |
ternary | 868451008.0 Ops/sec |
math | 863787392.0 Ops/sec |
What is tested?
The provided JSON represents a JavaScript microbenchmark test case, which measures the performance of different approaches to find the larger value between two variables.
There are three individual test cases:
if (a > b) { return a; } else { return b; }
) to compare a
and b
.a > b ? a : b
) to compare a
and b
. The ternary operator is a shorthand for an if-else statement.a * (a > b) + b * (b > a)
). This approach uses bitwise operations to determine which variable is larger.Options comparison
The three approaches have different pros and cons:
Library usage
None of the test cases use any JavaScript libraries or frameworks that would affect the performance measurement.
Special JS features or syntax
The ternary
test case uses a special syntax called the ternary operator (?:
), which is a shorthand for an if-else statement. This feature was introduced in ECMAScript 1999 and has since become a standard part of JavaScript.
Other alternatives
If you wanted to measure the performance of different approaches to find the larger value between two variables, you could also consider:
switch (a > b) { ... }
)a
and b
Math.max()
or Number.MAX_SAFE_INTEGER
However, these alternatives would likely have similar performance characteristics as the three approaches tested in this benchmark.