2

I'm working on a react custom renderer, which I have to shallow copy react props to the backend element, which there are reserved properties like "key", "ref", "children" I should filter out, especially the "children" conflicts with element's "children" property, Object.assign can't do that. I don't need to copy unkown properties, just a restricted set that matters.

I found something weird, compare with Object.assign, hard coding a switch statement inside iteration can get better performance on most modern browsers, and I found that compare to hand-written code, constructing a "Function" with generated code get even better performance(I'm not sure, it performs the same as the hand-writting one in my refactored code).

for (var key of Object.keys(source)) {
    switch (key) {
        case 'a': target.a = source.a; break;
        case 'b': target.b = source.b; break;
        // ....
    }
}

I have created several test cases:

https://jsperf.com/copy-known-properties-few

https://jsperf.com/copy-known-properties-many/4

https://jsperf.com/copy-known-properties-polymorphic

The second one included an extra case of constructed function.

Here is also a refactored version testing, more easy to read:

https://stackblitz.com/edit/limited-assign-perf

I wonder why and if this is practical, or are there even better ways.

My first question here, thanks.

  • https://mrale.ph/blog/2012/06/03/explaining-js-vms-in-js-inline-caches.html (and other good resources you will find with the keywords "js engine polymorphic inline cache") should answer this. – Bergi Oct 24 '18 at 18:32
  • why would you even need a switch for that? `target[key] = source[key]` – epascarello Oct 24 '18 at 18:34
  • 1
    No, this is absolutely not practical. Use it only if you identified `Object.assign` as an actual performance bottleneck. I would then recommend to give the particular class a `copyTo` method. Don't use a loop, don't use switch, don't write a generic function if you need this. – Bergi Oct 24 '18 at 18:35
  • Only your `randomSource()` creates the kinds of objects that `Object.assign` is optimised for: arbitrary ones. Of course custom-built ones that know the property names beforehand can run faster than a generic one. – Bergi Oct 24 '18 at 18:39
  • @Bergi Again, thanks for your reference link, I'm reading it and see what can I find. – fightingcat Oct 24 '18 at 18:58

0 Answers0