const obj = {
hello: "world"
};
if (Math.random()>.5) {
obj.foo = "bar";
}
const obj = {
hello: "world",
Math.random()>.5 && { foo: "bar" }
};
const obj = Object.assign({
hello: "world"
}, Math.random()>.5 && {
foo: "bar"
});
const obj = {
hello: "world"
};
Math.random()>.5 ? obj.foo = "bar" : false
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
boring | |
spread | |
Object.assign | |
Terinary |
Test name | Executions per second |
---|---|
boring | 9409034.0 Ops/sec |
spread | 6808347.5 Ops/sec |
Object.assign | 4095814.0 Ops/sec |
Terinary | 11231471.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark measures the performance of three different approaches to conditionally insert properties into an object: the ternary operator, spread syntax, and Object.assign()
.
Benchmark Definitions
obj.foo = "bar"
if (Math.random() > 0.5)
. The purpose of this benchmark is to test the performance of assigning properties dynamically....
) to create a new object with conditionally included properties. The syntax is: { ...Math.random() > .5 && { foo: "bar" } }
. The purpose of this benchmark is to test the performance of using the spread operator for dynamic property creation.Object.assign()
method to merge two objects, conditionally including properties. The syntax is: Object.assign({ hello: "world" }, Math.random() > .5 && { foo: "bar" })
. The purpose of this benchmark is to test the performance of using Object.assign()
for dynamic property assignment.Comparison
Approach | Description |
---|---|
Ternary Operator | Simple, direct assignment with a single expression. Pros: easy to read, concise. Cons: might be slower due to parsing overhead. |
Spread Syntax | More expressive and flexible than ternary operator. Pros: readable, maintainable code. Cons: may introduce additional overhead due to object creation. |
Object.assign() | Powerful method for merging objects, but can have performance implications if not optimized correctly. Pros: versatile, powerful. Cons: might be slower due to method invocation overhead. |
Library Usage
None of the benchmark definitions use a library explicitly.
Special JS Features or Syntax
--experimental-features
option, but it's not enabled by default.Other Alternatives
If you're interested in comparing performance of other approaches for conditionally inserting properties into an object, here are a few alternatives:
{ hello: "world", foo: ${Math.random() > 0.5 ? "bar" : null} }
.?
operator (introduced in ECMAScript 2020): `const obj = { hello: "world" }; const foo = Math.random() > 0.5 ? "bar" : undefined; Object.defineProperty(obj, "foo", { value: foo });Keep in mind that each alternative has its own trade-offs and potential performance implications, which may or may not be relevant depending on the specific use case.