Reputation: 1388
Good day. I can not understand which approach is best to use: calculate property at the moment of accessing it or calculate property every time it must be changed. For example, two approaches of implementing the Level property:
public class TreeNode
{
public TreeNode()
{
ChildNodes = new Collection<TreeNode>();
}
public Collection<TreeNode> ChildNodes { get; private set; }
public TreeNode ParentNode { get; private set; }
public int Level
{
get
{
if (ParentNode != null) return ParentNode.Level + 1;
else return 0;
}
}
pubic void Add(TreeNode node)
{
this.ChildNodes.Add(node);
node.ParentNode = this;
}
public void TraverseNodes(Action<TreeNode> action)
{
action(this);
foreach (CTreeNode child in this.ChildNodes)
{
child.TraverseNodes(action);
}
}
}
Best to use the above or below?
public class TreeNode
{
public TreeNode()
{
ChildNodes = new Collection<TreeNode>();
Level = 0;
}
public Collection<TreeNode> ChildNodes { get; private set; }
public TreeNode ParentNode { get; private set; }
public int Level { get; private set; }
pubic void Add(TreeNode node)
{
this.ChildNodes.Add(node);
node.ParentNode = this;
node.TraverseNodes(eachNode =>
{
eachNode.Level += this.Level + 1;
});
}
public void TraverseNodes(Action<TreeNode> action)
{
action(this);
foreach (CTreeNode child in this.ChildNodes)
{
child.TraverseNodes(action);
}
}
}
Upvotes: 0
Views: 80
Reputation: 11840
Some questions you can ask yourself are:
In your case, there is an overhead for the second solution you propose - you are calling TraverseNodes for a potentially large number of nodes whenever the tree changes. This is expensive.
On the other hand, calculating the property recursively on demand (your first solution) will be done each time you access the node - which becomes a problem if you're likely to access the Level
property a lot.
So it all depends how much you'll be using the Level
property. If you're using it a lot, and not adding things to the tree very often, consider using the second solution.
If you're constantly changing the tree, and not looking at Level
very much, it might be better to use your first approach.
However, your best bet is to try them both out with a typical usage scenario, and benchmark. Then you get a definite answer.
Upvotes: 1