Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Perf improvement.
  • Loading branch information
StephenMolloy committed Oct 29, 2021
commit 454a9fee80f2b3f3b67a6a906841245179e12ef8
Original file line number Diff line number Diff line change
Expand Up @@ -22,37 +22,40 @@ public ContextAwareTables()

internal T GetOrCreateValue(Type t, Func<T> f)
{
T? ret;
// The fast and most common default case
T? ret = (T?)_defaultTable[t];
if (ret != null)
return ret;

// Common case for collectible contexts
if (_collectibleTable.TryGetValue(t, out ret))
return ret;

// Not found. Do the slower work of creating the value in the correct collection.
AssemblyLoadContext? alc = AssemblyLoadContext.GetLoadContext(t.Assembly);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How expensive is ALC.GetLoadContext? If it's non-trivial, it might be worth always checking the default table first and only using GetLoadContext to see which table is should go in if not found in the default. If it's cheap, then this is fine.

// Null and non-collectible load contexts use the default table
if (alc == null || !alc.IsCollectible)
{
if ((ret = (T?)_defaultTable[t]) == null)
lock (_defaultTable)
{
lock (_defaultTable)
if ((ret = (T?)_defaultTable[t]) == null)
{
if ((ret = (T?)_defaultTable[t]) == null)
{
ret = f();
_defaultTable[t] = ret;
}
ret = f();
_defaultTable[t] = ret;
}
}
}

// Collectible load contexts should use the ConditionalWeakTable so they can be unloaded
else
{
if (!_collectibleTable.TryGetValue(t, out ret))
lock (_collectibleTable)
{
lock (_collectibleTable)
if (!_collectibleTable.TryGetValue(t, out ret))
{
if (!_collectibleTable.TryGetValue(t, out ret))
{
ret = f();
_collectibleTable.AddOrUpdate(t, ret);
}
ret = f();
_collectibleTable.AddOrUpdate(t, ret);
}
}
}
Expand Down