Skip to content

Commit

Permalink
Only allocate Lazy<> and lambda when necessary
Browse files Browse the repository at this point in the history
The local function avoid allocating a lambda when not used.
For more details, see: dotnet/roslyn#20777
  • Loading branch information
jnyrup committed Mar 24, 2024
1 parent e760ba4 commit ba6028b
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions Src/FluentAssertions/Execution/AssertionScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,17 +108,26 @@ private AssertionScope(IAssertionStrategy assertionStrategy, Lazy<string> contex
reason = parent.reason;
callerIdentityProvider = parent.callerIdentityProvider;
FormattingOptions = parent.FormattingOptions.Clone();
Context = new Lazy<string>(() => JoinContext(parent.Context, context));
Context = JoinContexts(parent.Context, context);
}
else
{
Context = context;
}
}

private static string JoinContext(params Lazy<string>[] contexts)
private static Lazy<string> JoinContexts(Lazy<string> outer, Lazy<string> inner)
{
return string.Join("/", contexts.Where(ctx => ctx is not null).Select(x => x.Value));
return (outer, inner) switch
{
(null, null) => null,
({ } a, null) => a,
(null, { } b) => b,
({ } a, { } b) => Join(a, b)
};

static Lazy<string> Join(Lazy<string> outer, Lazy<string> inner) =>
new(() => outer.Value + "/" + inner.Value);
}

/// <summary>
Expand Down

0 comments on commit ba6028b

Please sign in to comment.