Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reflection cache #155

Merged
merged 4 commits into from
Apr 16, 2021
Merged
Changes from all commits
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
31 changes: 31 additions & 0 deletions src/SmartFormat/Extensions/ReflectionSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// Licensed under the MIT license.
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SmartFormat.Core.Extensions;
Expand All @@ -11,6 +13,10 @@ namespace SmartFormat.Extensions
{
public class ReflectionSource : ISource
{
private static readonly object[] Empty = Array.Empty<object>();

private readonly Dictionary<(Type, string?), (FieldInfo? field, MethodInfo? method)> _typeCache = new();

public ReflectionSource(SmartFormatter formatter)
{
// Add some special info to the parser:
Expand All @@ -32,6 +38,24 @@ public bool TryEvaluateSelector(ISelectorInfo selectorInfo)
// Let's see if the argSelector is a Selectors/Field/ParseFormat:
var sourceType = current.GetType();

// Check the type cache
if (_typeCache.TryGetValue((sourceType, selector), out var found))
{
if (found.field != null)
{
selectorInfo.Result = found.field.GetValue(current);
return true;
}

if (found.method != null)
{
selectorInfo.Result = found.method.Invoke(current, Empty);
return true;
}

return false;
}

// Important:
// GetMembers (opposite to GetMember!) returns all members,
// both those defined by the type represented by the current T:System.Type object
Expand All @@ -45,6 +69,7 @@ public bool TryEvaluateSelector(ISelectorInfo selectorInfo)
// Selector is a Field; retrieve the value:
var field = (FieldInfo) member;
selectorInfo.Result = field.GetValue(current);
_typeCache[(sourceType, selector)] = (field, null);
return true;
case MemberTypes.Property:
case MemberTypes.Method:
Expand Down Expand Up @@ -72,11 +97,17 @@ public bool TryEvaluateSelector(ISelectorInfo selectorInfo)
// Make sure that this method is not void! It has to be a Function!
if (method?.ReturnType == typeof(void)) continue;

// Add to cache
_typeCache[(sourceType, selector)] = (null, method);

// Retrieve the Selectors/ParseFormat value:
selectorInfo.Result = method?.Invoke(current, new object[0]);
return true;
}

// We also cache failures so we dont need to call GetMembers again
_typeCache[(sourceType, selector)] = (null, null);

return false;
}
}
Expand Down