Skip to content

Commit 00cb1d1

Browse files
committed
Optimized lookup performance for PolicyList
1 parent 393b352 commit 00cb1d1

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

src/Container/PolicyList.cs

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ public class PolicyList : IPolicyList
1212
{
1313
#region Fields
1414

15+
private readonly object _sync = new object();
1516
private readonly IPolicyList _innerPolicyList;
16-
private readonly IDictionary<PolicyKey, IBuilderPolicy> _policies =
17-
new ConcurrentDictionary<PolicyKey, IBuilderPolicy>(PolicyKeyEqualityComparer.Default);
17+
private IDictionary<PolicyKey, IBuilderPolicy> _policies = null;
1818

1919
#endregion
2020

@@ -47,20 +47,20 @@ public PolicyList(IPolicyList innerPolicyList)
4747
/// <value>
4848
/// The number of items in the locator.
4949
/// </value>
50-
public int Count => _policies.Count;
50+
public int Count => _policies?.Count ?? 0;
5151

5252

5353
public void Clear(Type type, string name, Type policyInterface)
5454
{
55-
_policies.Remove(new PolicyKey(type, name, policyInterface));
55+
_policies?.Remove(new PolicyKey(type, name, policyInterface));
5656
}
5757

5858
/// <summary>
5959
/// Removes all policies from the list.
6060
/// </summary>
6161
public void ClearAll()
6262
{
63-
_policies.Clear();
63+
_policies = null;
6464
}
6565

6666
/// <summary>
@@ -76,8 +76,9 @@ public void ClearDefault(Type policyInterface)
7676
public IBuilderPolicy Get(Type type, string name, Type policyInterface, out IPolicyList list)
7777
{
7878
list = null;
79+
IBuilderPolicy policy = null;
7980

80-
if (0 < _policies.Count && _policies.TryGetValue(new PolicyKey(type, name, policyInterface), out var policy))
81+
if (_policies?.TryGetValue(new PolicyKey(type, name, policyInterface), out policy) ?? false)
8182
{
8283
list = this;
8384
return policy;
@@ -89,6 +90,14 @@ public IBuilderPolicy Get(Type type, string name, Type policyInterface, out IPol
8990

9091
public void Set(Type type, string name, Type policyInterface, IBuilderPolicy policy)
9192
{
93+
if(null == _policies)
94+
{
95+
lock (_sync)
96+
{
97+
if (null == _policies)
98+
_policies = new ConcurrentDictionary<PolicyKey, IBuilderPolicy>(PolicyKeyEqualityComparer.Default);
99+
}
100+
}
92101
_policies[new PolicyKey(type, name, policyInterface)] = policy;
93102
}
94103

0 commit comments

Comments
 (0)