var MergeState = (function () {
function MergeState() {
this.writeVersion = 0;
this.deepInspect = false;
}
MergeState.prototype.derive1 = function () {
var ret = new MergeState();
ret.writeVersion = this.writeVersion;
ret.deepInspect = this.deepInspect;
return ret;
};
MergeState.prototype.derive2 = function () {
var ret = {};
Object.setPrototypeOf(ret, this);
return ret;
};
return MergeState;
}());
var base = new MergeState();
var der = base.derive1();
var der = base.derive2();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Manual clone | |
Prototype |
Test name | Executions per second |
---|---|
Manual clone | 9802892.0 Ops/sec |
Prototype | 1620940.2 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition:
The benchmark tests two approaches to cloning an object in JavaScript:
MergeState
class using the new
keyword, just like creating any other object in JavaScript.Object.setPrototypeOf()
method to set the prototype of a new object (ret
) to the current instance (this
).Options Compared:
The benchmark compares the performance of these two approaches:
new
keyword)Object.setPrototypeOf()
)Pros and Cons:
Library and Purpose:
The MergeState
class is used as a test subject for this benchmark. It has two methods:
derive1()
: Creates a new instance of MergeState
using the new
keyword.derive2()
: Returns an object that shares its prototype with the current instance.The base
variable is an instance of MergeState
.
Special JS Feature or Syntax:
This benchmark does not use any special JavaScript features or syntax, such as async/await, generators, or arrow functions.
Other Alternatives:
If you're interested in exploring alternative approaches to cloning objects, consider the following:
cloneDeep()
function, which can create a deep copy of an object.JSON.parse(JSON.stringify(obj))
or Array.prototype.slice.call(obj)
.