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

fix: faster shallowEqual 30% performance improvement & __DEV__ Just make a judgment once #28776

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 5 additions & 7 deletions packages/react/src/ReactMemo.js
Expand Up @@ -15,6 +15,11 @@ export function memo<Props>(
type: React$ElementType,
compare?: (oldProps: Props, newProps: Props) => boolean,
) {
const elementType = {
$$typeof: REACT_MEMO_TYPE,
type,
compare: compare === undefined ? null : compare,
};
if (__DEV__) {
if (!isValidElementType(type)) {
console.error(
Expand All @@ -23,13 +28,6 @@ export function memo<Props>(
type === null ? 'null' : typeof type,
);
}
}
const elementType = {
$$typeof: REACT_MEMO_TYPE,
type,
compare: compare === undefined ? null : compare,
};
if (__DEV__) {
let ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
Expand Down
25 changes: 10 additions & 15 deletions packages/shared/shallowEqual.js
Expand Up @@ -29,26 +29,21 @@ function shallowEqual(objA: mixed, objB: mixed): boolean {
return false;
}

const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
let aLength = 0;
let bLength = 0;

if (keysA.length !== keysB.length) {
return false;
}

// Test for A's keys different from B.
for (let i = 0; i < keysA.length; i++) {
const currentKey = keysA[i];
if (
!hasOwnProperty.call(objB, currentKey) ||
// $FlowFixMe[incompatible-use] lost refinement of `objB`
!is(objA[currentKey], objB[currentKey])
) {
for (const key in objA) {
aLength += 1;
if (!hasOwnProperty.call(objB, key) || !is(objA[key], objB[key])) {
return false;
}
}

return true;
for (const _ in objB) {
bLength += 1;
}

return aLength === bLength;
}

export default shallowEqual;