I'm trying to create a "patch" between two objects in javascript to have only updated data in one variable.
var patch = {};
var o = {
id: 'p1',
kind: 'product',
title: 'ProductTitle',
price: 100,
stock: 10,
};
var n = {
title: 'ProductTitleRenamed',
price: 100,
stock: 20,
};
var patchExpected = {
title: 'ProductTitleRenamed',
stock: 20,
};
I tried multiple scenarios on jsperf with vanilla/lodash methods and I don't understand why the last is so slow compared to others (I guess it's related to string access). The raw version is logically faster (with many if) but it's really verbose, do you know other elegant and performant solution (using immutablejs, es6 map etc) ?
Testing in Chrome 58.0.3029 / Mac OS X 10.12.4
1 - With lodash loop on new object properties (3,006,759 ops/s)
_.forEach(n, (value, key) => {
if (value !== o[key]) {
patch[key] = value;
}
});
2 - With many if (17,873,849 ops/s)
if (!_.isUndefined(n.id) && o.id !== n.id) {
patch.id = n.id;
}
if (!_.isUndefined(n.kind) && o.kind !== n.kind) {
patch.kind = n.kind;
}
if (!_.isUndefined(n.title) && o.title !== n.title) {
patch.title = n.title;
}
if (!_.isUndefined(n.price) && o.price !== n.price) {
patch.price = n.price;
}
if (!_.isUndefined(n.stock) && o.stock !== n.stock) {
patch.stock = n.stock;
}
3 - With many if using util function "isChanged" (15,146,180 ops/s)
function isChanged(n, o) {
return !_.isUndefined(n) && o !== n;
}
if (isChanged(n.id, o.id)) {
patch.id = n.id;
}
if (isChanged(n.kind, o.kind)) {
patch.kind = n.kind;
}
if (isChanged(n.title, o.title)) {
patch.title = n.title;
}
if (isChanged(n.price, o.price)) {
patch.price = n.price;
}
if (isChanged(n.stock, o.stock)) {
patch.stock = n.stock;
}
4 - With one diff function (less verbose) (4,360,005 ops/s)
function diff(field) {
if (!_.isUndefined(n[field]) && o[field] !== n[field]) {
patch[field] = n[field];
}
}
diff('id');
diff('kind');
diff('title');
diff('price');
diff('stock');