function foo(){}
foo.prototype = {
foo_prop: "foo val"
};
function bar(){}
var proto = new foo;
proto.bar_prop = "bar val";
bar.prototype = proto;
var inst = new bar;
console.log(inst.foo_prop);
console.log(inst.bar_prop);
function foo(){}
foo.prototype = {
foo_prop: "foo val"
};
function bar(){}
var proto = Object.create(
foo.prototype
);
proto.bar_prop = "bar val";
bar.prototype = proto;
var inst = new bar;
console.log(inst.foo_prop);
console.log(inst.bar_prop);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new operator | |
Object.create method |
Test name | Executions per second |
---|---|
new operator | 826351.2 Ops/sec |
Object.create method | 626736.0 Ops/sec |
Let's break down the provided benchmarking test cases and explain what is being tested.
Overview
The benchmark measures the performance difference between two approaches for inheritance in JavaScript: using the new
operator versus Object.create
.
Options Compared
There are two options being compared:
new
operator: This approach creates a new instance of an object by calling the constructor function and passing no arguments.Object.create()
: This approach creates a new object by cloning the prototype of another object.Pros and Cons of Each Approach
New Operator:
Pros:
Cons:
Object.create():
Pros:
Cons:
new
operatorLibrary Used: None
There is no explicit library used in these benchmarking tests. However, it's worth noting that both approaches rely on JavaScript's built-in Object
and Prototype
objects.
Special JS Feature/Syntax: None
No special JavaScript features or syntax are being tested in these benchmarking tests.
Other Considerations
new
operator might incur additional overhead due to the creation of a new prototype object.Object.create()
approach, the lookup process for the prototype chain is more explicit and potentially slower than when using the new
operator.Alternatives
Other approaches for inheritance in JavaScript include:
extends
.curry()
or bind()
to create reusable, composable functions.These alternatives may offer different trade-offs in terms of readability, performance, and complexity, depending on the specific use case and requirements.