Skip to content

Commit 055b93f

Browse files
author
Bart Koelman
committed
Avoid closure in hot code path to reduce allocations
1 parent d8510aa commit 055b93f

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/JsonApiDotNetCore/Serialization/ResponseModelAdapter.cs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,9 @@ private IDictionary<string, RelationshipObject> ConvertRelationships(IIdentifiab
213213

214214
foreach (RelationshipAttribute relationship in resourceContext.Relationships)
215215
{
216-
IncludeElementExpression includeElement = includeElements.FirstOrDefault(element => element.Relationship.Equals(relationship));
216+
IncludeElementExpression includeElement = GetFirstOrDefault(includeElements, relationship,
217+
(element, nextRelationship) => element.Relationship.Equals(nextRelationship));
218+
217219
RelationshipObject relationshipObject = ConvertRelationship(relationship, resource, requestKind, includeElement, includedCollection);
218220

219221
if (relationshipObject != null && fieldSet.Contains(relationship))
@@ -231,6 +233,22 @@ private IDictionary<string, RelationshipObject> ConvertRelationships(IIdentifiab
231233
return null;
232234
}
233235

236+
private static TSource GetFirstOrDefault<TSource, TContext>(IEnumerable<TSource> source, TContext context, Func<TSource, TContext, bool> condition)
237+
{
238+
// PERF: This replacement for Enumerable.FirstOrDefault() doesn't allocate a compiler-generated closure class <>c__DisplayClass.
239+
// https://www.jetbrains.com/help/resharper/2021.2/Fixing_Issues_Found_by_DPA.html#closures-in-lambda-expressions
240+
241+
foreach (TSource item in source)
242+
{
243+
if (condition(item, context))
244+
{
245+
return item;
246+
}
247+
}
248+
249+
return default;
250+
}
251+
234252
private RelationshipObject ConvertRelationship(RelationshipAttribute relationship, IIdentifiable leftResource, EndpointKind requestKind,
235253
IncludeElementExpression includeElement, IncludedCollection includedCollection)
236254
{

0 commit comments

Comments
 (0)