Avoid defineProperty when not needed

This lets us use the fast path for most object literal assignments and then utilizes the defineProperty path when there is a chance that we could hit the setter issue described in #357.

10x performance boosts seen for the six-speed test case, going from 200k operations/sec to 2M ops/sec.
This commit is contained in:
kpdecker 2015-06-25 09:22:03 -05:00
parent 0f70c76312
commit 1d83ad6cce

View File

@ -1,8 +1,18 @@
(function (obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
// Shortcircuit the slow defineProperty path when possible.
// We are trying to avoid issues where setters defined on the
// prototype cause side effects under the fast path of simple
// assignment. By checking for existence of the property with
// the in operator, we can optimize most of this overhead away.
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
});