class Holder {
constructor(init) {
Holder.internalAssign(this, init);
}
static has(instance, property) {
return Object.prototype.hasOwnProperty.call(instance, property);
}
static internalAssign(target, source) {
if (Holder.has(source, "a"))
target.a = source.a;
if (Holder.has(source, "b"))
target.b = source.b;
if (Holder.has(source, "c"))
target.c = source.c;
}
clone() {
return new Holder(this);
}
cloneWith(props) {
const cloned = this.clone();
Holder.internalAssign(cloned, props);
return cloned;
}
cloneWith2(props) {
const cloned = this.clone();
Object.assign(this, props);
return cloned;
}
mutate(mutation) {
const cloned = this.clone();
mutation(cloned);
return cloned;
}
}
var initHolder = new Holder({
a: "value of a",
b: "value of b",
c: 1
});
initHolder.cloneWith({ a: "changed a", b: "changed b" });
initHolder.cloneWith2({ a: "changed a", b: "changed b" });
initHolder.mutate(x => { x.a = "changed a"; x.b = "changed b" });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
cloneWith | |
cloneWith2 | |
mutate |
Test name | Executions per second |
---|---|
cloneWith | 549301.3 Ops/sec |
cloneWith2 | 768467.2 Ops/sec |
mutate | 1027458.9 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Definition
The provided JSON represents a JavaScript microbenchmark that tests the performance of three different methods for cloning and mutating an object: cloneWith
, cloneWith2
, and mutate
.
clone
method creates a new instance of the Holder
class, copying all its properties.cloneWith
method creates a clone of the original object using clone()
, and then updates it with new properties using internalAssign
.cloneWith2
method uses Object.assign()
to update the cloned object with new properties.mutate
method clones the original object using clone()
, applies a transformation function to the clone, and returns the mutated object.Options Compared
The benchmark compares the performance of these three methods:
cloneWith
: Creates a new instance of the Holder
class, copies all properties, and then updates it with new properties.cloneWith2
: Uses Object.assign()
to update the cloned object with new properties.mutate
: Clones the original object using clone()
, applies a transformation function to the clone, and returns the mutated object.Pros and Cons of Each Approach
cloneWith
: Pros:internalAssign()
call, which may incur overhead.cloneWith2
: Pros:Object.assign()
function.mutate
: Pros:Special Considerations
In the provided benchmark definition, there is no special JavaScript feature or syntax used beyond what's standard. However, in other scenarios, additional considerations might arise:
Holder
class uses ES6 classes, which provide a concise way to define objects and their behavior.{}
) for defining objects, which is a standard JavaScript syntax.Alternatives
If you wanted to implement an alternative clone or mutation method in this benchmark, some options could include: