标签云

微信群

扫码加入我们

WeChat QR Code


How efficient do you need it to be? Are you doing this over and over again in the client (or is this server side like Node)? The JSON stringify -> parse method is very slick even if not the most efficient.

2018年10月23日56分56秒

Otherwise, deep-copy means recursive looping...

2018年10月23日56分56秒

...also any circular references to deal with?

2018年10月23日56分56秒

I would be sure to benchmark alternatives against json decode+encode. It may seem lame to make strings only to decode them, but it's done in native optimized code- and in the end that may make it faster.

2018年10月23日56分56秒

RandyHall: Ah, I think I understand. If you're only really dealing with them one level deep at any given time, and if they're actual Arrays, then I'd just iterate the current Array and and build a new one using .slice() on its nested Arrays. It'll be extremely fast.

2018年10月23日56分56秒

I guess that map with its extra function invocations is much slower in the most browsers, though it could be optimized by inlining and then might perform better.

2018年10月24日56分56秒

Bergi: Yeah, the map version will take a small hit, but it's nice and clean.

2018年10月23日56分56秒

Wow, the map is really clean

2018年10月23日56分56秒

Currently we just need to call .slice(0) to clone an array. Use .slice() is ok but .slice(0) is faster.

2018年10月23日56分56秒

The downside to both of these methods is that they don't handle self-referential cycles - something that may or may not be important (not sure what the JSON version will do with it, but the second example will infinitely loop)

2018年10月23日56分56秒

Jeff I trust you, but can you give a (small) example? Just wanted to understand

2018年10月23日56分56秒

var x = {}; x.y = x; will hit the else statement every time deepCopy is called, and the JSON just plain can't handle self-references - it's innately tree-based

2018年10月23日56分56秒

What is r.prototype = obj.prototype; supposed to do? Seems very wrong to me

2018年10月23日56分56秒

RandyHall, Jeff: No, it does not. It just creates a property named prototype. This does not set inheritance, as __proto__ would do. Proper way: Object.create(Object.getPrototypeOf(obj)); as in Danny's answer

2018年10月23日56分56秒