Skip to content

Commit 7b50d32

Browse files
committed
Add TryParseMethodCache
1 parent 25e98ba commit 7b50d32

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/Http/Http.Extensions/src/RequestDelegateFactory.cs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
5+
using System.Collections.Concurrent;
56
using System.Diagnostics;
67
using System.IO;
78
using System.Linq;
@@ -53,6 +54,8 @@ public static class RequestDelegateFactory
5354
private static readonly MemberExpression StatusCodeExpr = Expression.Property(HttpResponseExpr, nameof(HttpResponse.StatusCode));
5455
private static readonly MemberExpression CompletedTaskExpr = Expression.Property(null, (PropertyInfo)GetMemberInfo<Func<Task>>(() => Task.CompletedTask));
5556

57+
private static ConcurrentDictionary<Type, MethodInfo?> TryParseMethodCache = new();
58+
5659
/// <summary>
5760
/// Creates a <see cref="RequestDelegate"/> implementation for <paramref name="action"/>.
5861
/// </summary>
@@ -278,7 +281,6 @@ private static Expression CreateResponseWritingMethodCall(MethodInfo methodInfo,
278281
// If we're calling TryParse and the WasTryParseFailureVariable indicates it failed, set a 400 StatusCode instead of calling the method.
279282
private static Expression CreateTryParseCheckingResponseWritingMethodCall(MethodInfo methodInfo, Expression? target, Expression[] arguments)
280283
{
281-
282284
// {
283285
// bool wasTryParseFailureVariable = false;
284286
// string tempSourceString;
@@ -553,9 +555,8 @@ private static MethodInfo GetEnumTryParseMethod()
553555
throw new Exception("static bool System.Enum.TryParse<TEnum>(string? value, out TEnum result) does not exist!!?!?");
554556
}
555557

556-
// TODO: Cache this.
557558
// TODO: Use InvariantCulture where possible? Or is CurrentCulture fine because it's more flexible?
558-
private static MethodInfo? FindTryParseMethod(Type type)
559+
private static MethodInfo? FindTryParseMethodUncached(Type type)
559560
{
560561
if (type.IsEnum)
561562
{
@@ -585,6 +586,11 @@ private static MethodInfo GetEnumTryParseMethod()
585586
return null;
586587
}
587588

589+
private static MethodInfo? FindTryParseMethod(Type type)
590+
{
591+
return TryParseMethodCache.GetOrAdd(type, FindTryParseMethodUncached);
592+
}
593+
588594
private static bool HasTryParseMethod(ParameterInfo parameter)
589595
{
590596
var nonNullableParameterType = Nullable.GetUnderlyingType(parameter.ParameterType) ?? parameter.ParameterType;

0 commit comments

Comments
 (0)