var values = Array.from({length: 10000}, (_, i) => i % 5 === 0 ? i % 3 === 0 : i % 2 ? i.toString() : i);
let bools = 0;
for (let i = 0; i < values.length; i++) {
const value = values[i];
if (typeof value === "boolean") {
bools++;
}
}
let bools = 0;
for (let i = 0; i < values.length; i++) {
const value = values[i];
if (value === true || value === false) {
bools++;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
typeof value === "boolean" | |
value === true || value === false |
Test name | Executions per second |
---|---|
typeof value === "boolean" | 23981.9 Ops/sec |
value === true || value === false | 9623.1 Ops/sec |
Let's break down the JavaScript microbenchmark provided by MeasureThat.net.
Benchmark Definition
The benchmark measures the performance difference between two approaches to check if a value is a boolean:
typeof value === "boolean"
: This method checks the type of the value using the typeof
operator.value === true || value === false
: This approach uses a simple conditional statement to check if the value is either true
or false
.Options compared
The benchmark compares the performance of these two approaches, which can be thought of as:
typeof
to check the type of a value.true
and false
.Pros and Cons of each approach:
typeof value === "boolean"
):value === true || value === false
):Library and special JS features
There are no libraries or special JavaScript features used in this benchmark. The code is straightforward and only uses native JavaScript operators and data types.
Other considerations
Keep in mind that the performance difference between these two approaches may not be significant for most use cases, but it can add up when working with large datasets.
Alternatives
If you need to check if a value is a boolean in your code, typeof
might still be a good choice. However, for large datasets or performance-critical code paths, using a simple comparison like value === true || value === false
might be more efficient.
It's worth noting that some JavaScript engines, like V8 (used by Chrome), have optimized the typeof
operator to be faster for certain types of values.