var cls = function() {},
f = Object.getPrototypeOf,
s = Object.prototype,
constructorObject = function(a) {
return (!!a) && (a.constructor === Object);
},
prototypeObject = function(a) {
return f(a) === s;
};
var obj = {};
prototypeObject(obj);
prototypeObject(new cls);
constructorObject(obj);
constructorObject(new cls);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
prototype | |
constructor |
Test name | Executions per second |
---|---|
prototype | 32732250.0 Ops/sec |
constructor | 122359800.0 Ops/sec |
I'll explain the test cases, options compared, and other considerations for the provided JavaScript microbenchmark.
Benchmark Definition
The benchmark measures the performance difference between checking if an object is a constructor (constructorObject
) versus checking if an object's prototype is equal to the Object.prototype
(prototypeObject
). The benchmark creates two objects: obj
(an empty object) and cls
(a constructor function).
Options Compared
There are two options being compared:
prototypeObject(obj)
: This option checks if the prototype of an object obj
is equal to Object.prototype
. It does this by using the f
variable, which refers to Object.getPrototypeOf
, and comparing it with s
, which refers to Object.prototype
.constructorObject(obj)
: This option checks if the constructor of an object obj
is equal to Object.constructor
. It returns a boolean value indicating whether the constructor matches.Pros and Cons
prototypeObject(obj)
:Object.prototype
, which might be faster since it doesn't involve a function call.Object.prototype
, this test will still pass, even if the constructor is not a constructor (e.g., if the object has a custom prototype chain).constructorObject(obj)
:prototypeObject
since it's less dependent on the order of inheritance.Other Considerations
Object.getPrototypeOf
(which is available in modern browsers) ensures that the comparison is done correctly even if the object's prototype is not directly set to Object.prototype
.obj
and cls
. This could potentially introduce overhead due to object creation, but it's likely negligible compared to the performance differences between the two options.Library/Functionality
The prototypeObject
function uses Object.getPrototypeOf
, which is a part of the ECMAScript standard. Object.prototype
is also a built-in constant in JavaScript.
Special JS Feature/Syntax
There are no special features or syntaxes used in this benchmark that would make it specific to certain browsers or environments.
Alternatives
Other alternatives for measuring object prototype checking performance might include:
fast-prototypes
(which provides an optimized implementation of Object.getPrototypeOf
)Set.prototype.size
, which can be used to measure the number of unique objects