Why a hard-coding switch performs better at restricted shallow copying?

84 Views Asked by At

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.

0

There are 0 best solutions below