var values = [1, [1, 2, 3], undefined, [4], undefined, 5];
let wrapped;
for (const value of values) {
wrapped = typeof value === "undefined" ? [] : Array.isArray(value) ? value : [value];
}
let wrapped;
for (const value of values) {
wrapped = !value ? [] : Array.isArray(value) ? value : [value];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
typeof | |
boolean conversion |
Test name | Executions per second |
---|---|
typeof | 1061979.1 Ops/sec |
boolean conversion | 1052107.2 Ops/sec |
Let's dive into the explanation of the provided benchmark.
What is tested?
The benchmark tests two different approaches to wrapping values in an array:
approach: This approach uses the
typeof` operator to check if a value is "undefined", and if so, wraps it in an empty array. If the value is an array itself, it leaves it unchanged. If not, it creates a new array with the value.approach: This approach uses a simple boolean conversion to wrap values in an array. It checks if the value is "falsey" (i.e.,
undefined,
null,
0,
-0,
''`, etc.), and if so, wraps it in an empty array.Options compared
The two approaches are compared in terms of their performance and memory usage.
Pros and Cons
typeof
operator.Library usage
None of the benchmark tests use any external libraries.
Special JS feature or syntax
Neither test case uses any special JavaScript features or syntax. They are straightforward, vanilla JavaScript implementations.
Other alternatives
There may be other approaches to wrapping values in an array, such as using Array.isArray()
and conditional statements, or using a library like Lodash's compact()
function. However, these alternatives are not tested by the provided benchmark.
The benchmark provides two test cases: "typeof" and "boolean conversion". The results indicate that the boolean conversion approach is slightly faster than the "typeof" approach. This may be due to the performance characteristics of Safari 13 on Mac OS X 10.14.6, but it's also worth noting that the difference is relatively small (about 5%).
Overall, this benchmark provides a simple and informative test case for comparing different approaches to wrapping values in an array, which can be useful for optimizing performance-critical code.