const x = {
foo: []
};
const keys = ["foo", "bar"];
for (const key of keys) {
if (!Object.prototype.hasOwnProperty.call(x, key)) {
x[key] = [];
}
}
const x = {
foo: []
};
const keys = ["foo", "bar"];
for (const key of keys) {
x[key] = x[key] ?? [];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
if condition | |
self-assignment |
Test name | Executions per second |
---|---|
if condition | 7527238.0 Ops/sec |
self-assignment | 31347188.0 Ops/sec |
I'd be happy to explain the benchmark and its results.
Benchmark Description
The benchmark measures the performance difference between two approaches: using an if
condition to check for property existence, and using self-assignment (x[key] = x[key] ?? []
) to initialize missing properties in an object.
Options Compared
The two options being compared are:
x
before assigning a new value to it.??
) to assign an empty array to missing properties in a single statement.Pros and Cons of Each Approach
Library and Purpose
Neither of these approaches relies on any external libraries. However, they do utilize some built-in JavaScript features:
Object.prototype.hasOwnProperty.call()
: This method checks if an object has a certain property.??
): This operator returns the first operand if it's not null or undefined; otherwise, it returns the second operand.Special JS Feature
The self-assignment approach uses the nullish coalescing operator (??
), which is a relatively recent feature introduced in ECMAScript 2020. This operator allows for concise way to handle null or undefined values.
Other Considerations
When writing performance-critical code, it's essential to consider the trade-offs between readability, maintainability, and execution speed. In this case, the self-assignment approach is likely to be faster since it involves a single statement, whereas the if
condition approach may incur additional overhead due to the check.
Alternatives
If you don't want to use JavaScript's nullish coalescing operator or if you prefer an even more concise approach, you can consider using the following alternatives:
in
operator: Instead of Object.prototype.hasOwnProperty.call()
, you can use the in
operator to check if a property exists in the object.for (const key of keys) {
x[key] = Array.isArray(x[key]) ? [] : [];
}
...
): You can use the spread operator to initialize missing properties with an empty array.for (const key of keys) {
x[key] = [...x[key], []];
}
However, these alternatives may have different performance characteristics and may not be as concise or readable as the self-assignment approach.