This is a benchmark of various different strategies for creating clones of an object whose structure is known ahead of time.
In this test we assume that we always want to produce a clone of the same object and that the object contains no circular references, outside pointers, or non-JSON-serializable objects.
The use-case for such cloning is to have a "template" data structure that then gets copied and mutated for each request, leaving the template untouched. This is useful if only a small part of the data structure gets altered on each request and most of it remains set to what is in the template.
In all cases the functions were written to do as much as possible ahead of time so that the copy function could execute as quickly as possible. (Some variants on pre-processing were tried and eliminated before arriving at this final test set. The rejected variants are not reflected in the results or the source code.)
All results are over 10,000,000 iterations.
Test | Copy | Write | Read |
---|---|---|---|
json | 23210ms | 145ms | 173ms |
manual | 11669ms | 194ms | 304ms |
inherit | 11880ms | 67ms | 337ms |
function | 315ms | 61ms | 288ms |
Copying by pre-compiling to a function is the clear winner, presumably because it reduces to the evaluation of an object literal which V8 is tuned to do fast due to it being a very common construct in idiomatic JavaScript.
Didn't get to the bottom of this exactly, but tried running the tests again over 100,000,000 iterations to get a bit more resolution, and the trend remained.
Reversed the order of running the tests and the progression did not reverse along with it, suggesting that those numbers have nothing to do with the copying strategy and more to do with how V8 optimizes (or rather, de-optimizes) the test code as we introduce more differently-shaped objects into the mix.
Thus the Write and Read times are not meaningful for the purpose of this test, except to say that there seems to be negligible difference between reading and writing the object structures produced by each of these functions.
To re-validate the "copy" results, re-ran those in reverse order too and found that in this case the trend remained, suggesting that the differences here are significant.