MaiaVictor
MaiaVictor

Reputation: 53017

Why JSON is faster to clone an object than `for in` and `map`?

Using the functions below to deeply clone a tree,

function clone_map(obj){
    return obj.map(function(val){
        return typeof(val) == "object" ? clone_map(val) : val;
    });
};
function clone_forin(obj){
    var result = [];
    for (var key in obj){
        var val = obj[key];
        result.push(typeof(val) == "object" ? clone_forin(val) : val);
    };
    return result;
};
function clone_json(obj){
    return JSON.parse(JSON.stringify(obj));
};

The JSON one is the fastest on my tests. Why? And is there a better option?

Upvotes: 3

Views: 539

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075059

As you can see from subsequent tests, the JSON option is faster on some versions of Chrome, but not on Safari or Firefox. You'll probably find a mix in other browsers as well.

Your JavaScript cloning code is in JavaScript. A browser is free to implement JSON.stringify and JSON.parse in highly optimized machine code. (It's also free to compile your JavaScript into optimized machine code if it feels it needs to.) So it's no great surprise that sometimes, a fairly simple array such as the one you tested with might be faster via JSON than not. On some engines. With some sets of sample data. And that on other engines (or with other sets of sample data), there's a different result.

It's also worth noting that the difference isn't massive, not in any real world sense. The JSON option is about 25% faster than its nearest competitor in the tests shown in Chrome 24. But each individual iteration is so blindingly fast that it makes no real-world difference. 392k ops/sec vs. 521k ops/sec, it's still a shedload of ops/sec. :-)

Upvotes: 4

Related Questions