var elements = [0, 1, false, 2, '', 3, undefined, 'abc', 'de'];
elements.filter((e) => !!e)
elements.filter(Boolean)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
!! | |
Boolean |
Test name | Executions per second |
---|---|
!! | 14695390.0 Ops/sec |
Boolean | 6090662.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is being tested?
The provided JSON represents two benchmark test cases:
filter Boolean vs !!
: This test compares the performance of using the Boolean()
function versus the double-bang operator (!!
) in a filter method."elements.filter((e) => !!e)"
(using !!
): This test case filters an array of elements using the double-bang operator."elements.filter(Boolean)"
(using Boolean()
: This test case filters an array of elements using the built-in Boolean()
function.Options being compared
The two approaches being compared are:
!!
): A shorthand for converting a value to a boolean, where true
becomes 1 and false
becomes 0. In the context of filtering an array, this means that non-boolean values will be converted to booleans.Boolean()
function: This function explicitly converts its input to a boolean value.Pros and cons
!!
):Boolean()
function:Library usage
There is no explicit library mentioned in the provided JSON. However, if we look at the test cases, we can infer that the filter()
method is being used, which is a native JavaScript method.
Special JS features or syntax
The double-bang operator (!!
) is a special feature in JavaScript, but it's not explicitly mentioned as a special feature in this benchmark. However, it's worth noting that !!
can have unexpected behavior with certain types of values (e.g., objects, arrays).
Other alternatives
If you were to implement this benchmark yourself, here are some alternative approaches:
Boolean()
function, you could simply use a boolean value in the filter method.Here's some example code for each alternative:
// Using a boolean value directly
elements.filter(value => typeof value === 'boolean');
// Using an arrow function with explicit type conversion
elements.filter((value) => {
return Boolean(value);
});
Keep in mind that these alternatives may not be as concise or readable as the double-bang operator or the built-in Boolean()
function.
I hope this explanation helps!