function isObject(o) {
return Object.prototype.toString.call(o) === '[object Object]';
}
function isPlainObject(o) {
var ctor,prot;
if (isObject(o) === false) return false;
// If has modified constructor
ctor = o.constructor;
if (ctor === undefined) return true;
// If has modified prototype
prot = ctor.prototype;
if (isObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
};
const a = {a:1}
isPlainObject(a)
const a = {a:1}
a !== null && typeof a === 'object'
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
isPlainObject | |
typeof and null check |
Test name | Executions per second |
---|---|
isPlainObject | 1550293.5 Ops/sec |
typeof and null check | 946768256.0 Ops/sec |
Let's break down the provided benchmark and its options.
Benchmark Definition
The test case is defined by two functions: isObject
and isPlainObject
. The main function, isPlainObject
, checks if an object is a plain object (i.e., not a prototype or derived from another constructor). Here's what it does:
isObject
function to check if the object is of type Object
.isPrototypeOf
method (a property specific to Objects).Options compared
The two options being tested are:
isObject(o) === false
: This option simply checks if the object is not of type Object
. However, this approach has some drawbacks:Array
).isPlainObject(o)
: This option checks for the presence of the isPrototypeOf
method on the object's prototype, which is more robust and accurate.Pros and Cons
isObject(o) === false
:isPlainObject(o)
:Library
In the provided code, isObject
is not explicitly defined as a library, but rather as an anonymous function. However, in general, isObject
could be considered a utility function for checking if an object is of type Object
.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes being tested in this benchmark.
Alternatives
Other alternatives to implement the isPlainObject
check could include:
lodash.isPlainObject
(if you're using Lodash).isPrototypeOf
method on the object's prototype.constructor
property and then verifying its type.Keep in mind that this benchmark focuses on testing the specific implementation of isPlainObject
, so alternatives might not be directly comparable.