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

Benchmark for strategy creation #1426

Merged
merged 1 commit into from
Jul 24, 2023
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
```

BenchmarkDotNet v0.13.6, Windows 11 (10.0.22621.1992/22H2/2022Update/SunValley2) (Hyper-V)
Intel Xeon Platinum 8370C CPU 2.80GHz, 1 CPU, 16 logical and 8 physical cores
.NET SDK 7.0.306
[Host] : .NET 7.0.9 (7.0.923.32018), X64 RyuJIT AVX2

Job=MediumRun Toolchain=InProcessEmitToolchain IterationCount=15
LaunchCount=2 WarmupCount=10

```
| Method | Mean | Error | StdDev | Gen0 | Allocated |
|------------ |-----------:|---------:|---------:|-------:|----------:|
| Fallback_V7 | 114.8 ns | 1.84 ns | 2.70 ns | 0.0191 | 480 B |
| Fallback_V8 | 4,324.7 ns | 21.92 ns | 31.43 ns | 0.2518 | 6504 B |
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The creation in V8 is indeed more expensive as it involves a lot more infra. For this reason the recreation of strategies on hot path should be discouraged.

Copy link
Member

Choose a reason for hiding this comment

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

What would your generic recommendation be?

In the sandbox app the fallback behaviour is trivial and could be cached, but in the code on which it was based there's dynamic per-invocation behaviour going on to select the fallback.

It feels that to support the same behaviour the more performant option would be to drop Polly fallbacks entirely and deal with it at the call site like any "normal" code, which if true doesn't feel great that the performance for this scenario has actually gone backwards.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't think I have seen a scenario where you are "forced" to recreate a strategy on a hot path.

At worst you need to fallback to some dynamic value, but that can be archived by passing such value to the fallback action using ResilienceContext.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

In you code the caching could look like:

image

Copy link
Member

Choose a reason for hiding this comment

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

Could you paste the code rather than a picture of it? 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sure, I tried to create a draft PR to your repo and got rejected.

public ResilienceStrategy<TResult> GetStrategy<TResult>(ApiEndpointOption endpoint, bool handleExecutionFaults, string resource)
{
    return _registry.GetOrAddStrategy<TResult>($"fallback/{resource}/{handleExecutionFaults}", builder =>
    {
        var shouldHandle = new PredicateBuilder<TResult>()
            .Handle<ApiException>()
            .HandleHttpRequestFault()
            .Handle<TaskCanceledException>();

        if (handleExecutionFaults)
        {
            shouldHandle = shouldHandle
                .Handle<BrokenCircuitException>()
                .Handle<IsolatedCircuitException>()
                .Handle<TimeoutRejectedException>();
        }

        builder
            .AddStrategy(GetStrategy(endpoint, resource))
            .AddFallback(new FallbackStrategyOptions<TResult>()
            {
                FallbackAction = context =>
                {
                    if (context.Context.Properties.TryGetValue(FallbackKeys<TResult>.FallbackValue, out var value) && value != null)
                    {
                        return Outcome.FromResultAsTask(value());
                    }

                    return Outcome.FromResultAsTask<TResult>(default);
                },
                ShouldHandle = shouldHandle,
                StrategyName = $"{endpoint.Name} Fallback",
            });
    });
}

Copy link
Member

@martincostello martincostello Jul 24, 2023

Choose a reason for hiding this comment

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

Do you have the code for FallbackKeys?

Nevermind, I can see it in the screenshot.

Comment on lines +14 to +15
Copy link
Member

Choose a reason for hiding this comment

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

Wow that's a lot more 😅

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think validation eats a lot of that as it involves reflection.

25 changes: 25 additions & 0 deletions bench/Polly.Core.Benchmarks/CreationBenchmark.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace Polly.Core.Benchmarks;

#pragma warning disable CA1052 // Static holder types should be Static or NotInheritable

public class CreationBenchmark
{
[Benchmark]
public static void Fallback_V7()
{
Policy
.HandleResult<string>(s => true)
.FallbackAsync(_ => Task.FromResult("fallback"));
}

[Benchmark]
public static void Fallback_V8()
{
new ResilienceStrategyBuilder<string>()
.AddFallback(new()
{
FallbackAction = _ => Outcome.FromResultAsTask("fallback")
})
.Build();
}
}