var arr = Array.from({length: 10000}, () => Math.random() > 0.5 ? null : "foo");
const numTruthy = arr.filter(Boolean).length;
console.log(numTruthy);
const numTruthy = arr.filter(x => !!x).length;
console.log(numTruthy);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter(Boolean) | |
filter function |
Test name | Executions per second |
---|---|
filter(Boolean) | 41445.6 Ops/sec |
filter function | 40824.4 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition:
The benchmark is testing the performance of two approaches:
filter(Boolean)
: This is an idiomatic way to filter out falsy values from an array in JavaScript. The Boolean
function returns a value that is coerced to a boolean, which is then used as a predicate in the filtering process.Options Compared:
The benchmark is comparing the performance of two different approaches:
filter(Boolean)
: This approach uses the built-in Boolean
function to coerce falsy values to false
, which are then filtered out.Pros and Cons of Each Approach:
filter(Boolean)
:filter(Boolean)
, as it allows for arbitrary coercion logic.Library/Custom Function:
In this benchmark, no external library is used. However, the filter()
function itself is a built-in JavaScript method that returns an array of elements that pass the test implemented by the provided function.
Special JS Feature/Syntax:
There are no special JavaScript features or syntaxes mentioned in this benchmark. The focus is on comparing two different approaches to filtering arrays.
Other Considerations:
When writing benchmarks like this, it's essential to consider factors such as:
In this case, the benchmark provides a small array of 10,000 elements with an equal split between truthy and falsy values. The custom coercing function is used to coerce each element to a boolean value before applying the filter.
Alternatives:
Other alternatives for filtering arrays in JavaScript might include:
Array.prototype.filter()
with a callback functionHowever, in this benchmark, the focus is on comparing two specific approaches: filter(Boolean)
and filtering by a custom coercing function.