<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.js"></script>
var array = [undefined, 'cat', false, 434, '', 32.0]
_.compact(array)
array.filter(Boolean)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.compact | |
array.filter |
Test name | Executions per second |
---|---|
_.compact | 5356424.5 Ops/sec |
array.filter | 5353179.0 Ops/sec |
What is being tested?
The benchmark tests the performance of two approaches to remove undefined
values from an array: the _.compact()
function from the Lodash library, and the array.filter(Boolean)
method.
Options compared
There are two options being compared:
undefined
.Pros and Cons of each approach
_.compact()
Pros:
Cons:
Array.prototype.filter(Boolean)
Pros:
Cons:
Boolean
context function in JavaScriptOther considerations
Both approaches can be effective, but the choice between them depends on the specific use case and performance requirements. If readability and convenience are more important than raw performance, _.compact() might be a better choice. However, if every ounce of performance counts, using native JavaScript methods like filter(Boolean)
could be a better option.
Library explanation
The Lodash library is a popular collection of functional programming utilities in JavaScript. It provides many useful functions for tasks such as array manipulation, object iteration, and more. In this benchmark, the _.compact()
function is used to remove undefined
values from an array.
Special JS feature or syntax
No special JavaScript features or syntax are being tested in this benchmark. The code snippets provided use standard JavaScript syntax and methods.
Benchmark preparation code explanation
The script preparation code creates an array with undefined
values, which will be used as input for both tests: _.compact()
and array.filter(Boolean)
.