<!--your preparation HTML code goes here-->
var count = 1000;
var bool = true;
for (var i = 0; i <= count; i++) {
if (bool === true || bool === false) {
}
}
for (var i = 0; i <= count; i++) {
if (typeof(bool) === "boolean") {
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
literal comparison | |
typeof |
Test name | Executions per second |
---|---|
literal comparison | 151485.3 Ops/sec |
typeof | 197763.7 Ops/sec |
The benchmark being tested compares two different methods of evaluating Boolean values in JavaScript. Specifically, it contrasts the use of a literal comparison (bool === true || bool === false
) against using the typeof
operator (typeof(bool) === "boolean"
). Each of these methods serves to check if a value is a Boolean, but they do so in distinct ways, which can have implications for performance and readability.
Literal Comparison
if (bool === true || bool === false)
literal comparison
bool
is strictly equal to true
or false
. This method explicitly checks both possible states of a Boolean value.Typeof Operator
if (typeof(bool) === "boolean")
typeof
typeof
operator to check if bool
is of the boolean
type. This method does not involve explicit true/false conditions, but instead checks the data type directly.From the benchmark results:
typeof
method achieved approximately 197,764 executions per second.literal comparison
method achieved approximately 151,485 executions per second.Literal Comparison
Pros:
Cons:
typeof
, as it requires two comparisons and hence may consume more resources in a tight loop or performance-critical code.Typeof Operator
Pros:
typeof
operator.Cons:
typeof
string comparison, which some developers may find less straightforward than direct comparisons.typeof
method may be preferred. However, in scenarios where code readability and clarity are paramount, inline comparisons could be justified.Several alternative methods exist for checking Boolean values or types in JavaScript, including:
Boolean(bool)
could return the primitive boolean representation.!!bool
, although this checks truthiness rather than types explicitly.In summary, this benchmark provides insights into evaluating Boolean values efficiently, showcasing the trade-offs between performance and readability between different evaluation approaches. The results clearly suggest that using the typeof
operator is the more efficient route in terms of execution speed.