Increase speed of shallowEqual

All testes successfully completed.

- for-in in browsers is slow, i replaced him by Object.keys + for(array)
- simple check of lengths let us not iterate if not same
- now we dont need to test for B's keys missing from A, because if length's is same and prev check success - objB hasn't more keys
- micro optimize: calling objB.hasOwnProperty
- micro optimize: replaced !objA || !obj for more speedy check === null

#inspiredby https://github.com/jurassix/react-immutable-render-mixin/pull/4
This commit is contained in:
Murad
2015-04-02 23:43:29 +08:00
parent c8afa1833a
commit 9bc25326d9
+12 -14
View File
@@ -23,28 +23,26 @@ function shallowEqual(objA, objB) {
return true;
}
if (!objA || !objB) {
if (typeof objA !== 'object' || objA === null
|| typeof objB !== 'object' || objB === null) {
return false;
}
if (typeof objA !== 'object' || typeof objB !== 'object') {
var keysA = Object.keys(objA),
keysB = Object.keys(objB);
if(keysA.length !== keysB.length) {
return false;
}
var key;
// Test for A's keys different from B.
for (key in objA) {
if (objA.hasOwnProperty(key) &&
(!objB.hasOwnProperty(key) || objA[key] !== objB[key])) {
return false;
}
}
// Test for B's keys missing from A.
for (key in objB) {
if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) {
var bHasOwnProperty = objB.hasOwnProperty.bind(objB);
for(var i = 0, length = keysA.length; i < length; i++) {
if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]] ) {
return false;
}
}
return true;
}