What's faster: JSON.parse+stringify or extend/mixin?
Today I ran into the case, that I just wanted to clone a plain javascript object (no functions at all, just values). I was wondering whether it would be faster to use the native JSON.stringify+parse (which would include generating a very big string, just to throw it away):
or to use the javascript functions process.mixin/extend and perform a deep copy:
Here are the results:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
8691ms 3x JSON.parse(JSON.stringify(object))
5839ms 3x extend(true, {}, object)
JSON-String: 29959 characters
10305ms 3000x JSON.parse(JSON.stringify(object))
7445ms 3000x extend(true, {}, object)
JSON-String: 249 characters
214ms 3000x JSON.parse(JSON.stringify(object))
94ms 3000x extend(true, {}, object)
JSON-String: 39 characters
118ms 3000x JSON.parse(JSON.stringify(object))
32ms 3000x extend(true, {}, object)
The script is the following: http://gist.github.com/354628 and the Test PC was a i7-920 Quadcore with HT and 8GB DDR3 RAM.
In my test setup it was 2x faster to use a function like extend.
Messages
Well, no wonder. And it's not just creating thge unnecessary string but the whole parser-lexer thing involved in JSON methods (esp. stringify). Extend operates on memory structures, without parsing/lexing/whatevermore overhead.


