Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance #16

Merged
merged 4 commits into from
Jun 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions benchmark.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {inspect} from 'node:util';
import {runInNewContext} from 'node:vm';
import isPlainObject from 'is-plain-obj';

const runBenchmarks = () => {
for (const value of values) {
const name = value instanceof Error ? String(Error) : inspect(value);
const paddedName = name.padEnd(50);
console.time(paddedName);
runLoop(value);
console.timeEnd(paddedName);
}
};

const runLoop = value => {
for (let index = 0; index < 1e8; index += 1) {
isPlainObject(value);
}
};

const values = [
undefined,
0,
0n,
'',
true,
Symbol(''),
() => {},
// eslint-disable-next-line func-names
(function namedFunc() {}),
null,
{},
Math,
new Set([]),
new ArrayBuffer(0),
Promise.resolve(),
Object.create(null),
new Intl.Locale('en'),
// eslint-disable-next-line no-new-object
new Object({prop: true}),
new class Class {}(),
[],
/regexp/,
new Error('test'),
new Date(),
(function () {
// eslint-disable-next-line prefer-rest-params
return arguments;
})(),
new Proxy({}, {})
];

// Warm up V8 optimization.
// Must go through every branch of the code, which requires using an object from a different realm.
runLoop(runInNewContext('({})'));

runBenchmarks();
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
export default function isPlainObject(value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
if (typeof value !== 'object' || value === null) {
return false;
}

const prototype = Object.getPrototypeOf(value);
return prototype === null || Object.getPrototypeOf(prototype) === null;
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
}