C
C#2y ago
SWEETPONY

❔ Is it worth to create lazy dictionary in this case?

I have following class: so as you see Add function add to the dictionary class TreeNode, it looks like a tree I made a lazy dictionary and my question is: is it worth it? Will it be better with simple dictionary?
3 Replies
SWEETPONY
SWEETPONY2y ago
public class TreeNode
{
public readonly Lazy<Dictionary<string, TreeNode>> _treeChildren = new();

public bool Add(
string[] subTopic,
MqttDelivery delivery)
=> Add(subTopic, Level + 1, delivery);

private bool Add(
string[] topic,
int level,
MqttDelivery delivery)
{
if (level >= topic.Length)
{
Topic = delivery.Topic;
Header = delivery.Header?.ToJsonString( true );
Payload = delivery.Payload?.ToJsonString( true );
Delivery = delivery;
AddToHistory( delivery );

return false;
}

var part = topic[ level ];
if (!_treeChildren.Value.ContainsKey(part))
{
TopicsCount++;
_treeChildren.Value.Add( part, new TreeNode( part, level, this));
}

MessagesCount++;
_treeChildren.Value[ part ].Add( topic, level + 1, delivery ); return true;
}
}
public class TreeNode
{
public readonly Lazy<Dictionary<string, TreeNode>> _treeChildren = new();

public bool Add(
string[] subTopic,
MqttDelivery delivery)
=> Add(subTopic, Level + 1, delivery);

private bool Add(
string[] topic,
int level,
MqttDelivery delivery)
{
if (level >= topic.Length)
{
Topic = delivery.Topic;
Header = delivery.Header?.ToJsonString( true );
Payload = delivery.Payload?.ToJsonString( true );
Delivery = delivery;
AddToHistory( delivery );

return false;
}

var part = topic[ level ];
if (!_treeChildren.Value.ContainsKey(part))
{
TopicsCount++;
_treeChildren.Value.Add( part, new TreeNode( part, level, this));
}

MessagesCount++;
_treeChildren.Value[ part ].Add( topic, level + 1, delivery ); return true;
}
}
demidev_mb
demidev_mb2y ago
It's not a lazy dictionary, it's just lazily created dictionary. No it's not worth it Just use this
_treeChildren ??= new();
_treeChildren ??= new();
private readonly Dictionary<string, TreeNode> _treeChildren; // null
private readonly Dictionary<string, TreeNode> _treeChildren; // null
If it's public use property
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.