I have a hierarchy of nodes where the relevant part of the Node class looks like this:
public class Node
{
protected Node parent;
protected List<Node> children;
public Node Duplicate()
{
string json = JsonUtility.ToJson(this);
Node duplicate = (Node)JsonUtility.FromJson(json, GetType());
return duplicate;
}
}
(I use Unity's JsonUtility to serialize to JSON and then deserialize it. Should be the same with System.Text.Json)
Now I want to create a duplicate of a Node with all of its children, and so I do this:
Node duplicate = someNode.Duplicate();
Did I just create a deep copy of the hierarchy, or is it just another way to make a shallow copy?
Is JSON serialization and deserialization suitable for duplicating hierarchies where I want all of the data to be intact?
CodePudding user response:
You've definitely created a deep copy. This approach has one benefit: It works correctly. It has one drawback: Horrible performance. If that's not an issue, its simplicity is alluring.
And performance might not be an issue! It depends on your scenario.
