3 ms·
Missing from the benchmarks is simple deep copying: function deepClone (obj) { var clone = {} for (var key in obj) { if (obj.ha
by ricardobeat 9y ago
Missing from the benchmarks is simple deep copying:
function deepClone (obj) {
var clone = {}
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var value = obj[key]
switch (Object.prototype.toString.call(value)) {
case '[object Object]': clone[key] = deepClone(obj[key]); break
case '[object Array]' : clone[key] = value.slice(0); break
default : clone[key] = value
}
}
}
return clone
}
This is 5-10x faster than the JSON trick in WebKit: http://jsben.ch/W0ciO http://jsben.ch/W0ciO
(naive implementation, but covers 90% of uses, see lodash for the full mess: https://github.com/lodash/lodash/blob/master/.internal/baseClone.js https://github.com/lodash/lodash/blob/master/.internal/baseC...)
- drodgers 9y agoI believe that it's faster, but only because it's not actually deep-cloning. This: value.slice(0); is a shallow clone; it makes a new array, but doesn't clone it's contents.
- ricardobeat 9y agoHence being a 'naive' implementation. You can replace that with something like `deepClone(value)` + implement copying for different types, ultimately you'll end up with code like lodash's.
- drodgers 9y agoIt's not just naive though, it's wrong; it won't even give you new objects although it seems like it's meant-to: a = [1, {foo: "bar"}]; b = a.slice(0); b[1].foo = "baz"; console.log(a) > [1, {foo: "baz"}] console.log(b) > [1, {foo: "baz"}] A naive implementation would do this: case '[object Array]' : clone[key] = value.map((item) => deepClone(item)); break And would thus be slower.
- ricardobeat 9y agoWe are in agreement here. My suggestion was to make the deepClone method also take arrays, and walk through them copying values in the for loop (significantly faster than map). Again, I linked to a full implementation at the end; was more commenting on the lack of this particular approach, wrote this on the spot as an example.