You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This came up after a perf investigation on a recently refactored endpoint. Moving us back from IOptionsSnapshot to IOptionsMonitor knocked off ~100us, nothing else changed.
This option type of ours is fairly costly to create and looking into OptionsManager<TOptions> showed an obvious clue why we saw issues. OptionsManager does not just cache the instance for the duration of the DI scope but it also creates from scratch an instance through the factory per scope.
Looking through the docs this is vaguely alluded to (though there are contra-indicators) but after doing a search on SO and blogs on the subject most users seem to focus entirely on the 'you get a constant value during a scope/request' aspect of it.
As nobody (famous last words) seems to care whether it is entirely recreated my question would be:
Why doesn't OptionsManager<TOptions> cache the result of an IOptionsMonitor.Get call? (leaving out the backwards compatibility part for the sake of argument)
Reacted by Tom Pažourek, cr, Dmitriy Ivanov and JeffMathewSyngenta
Yes this is a known issue #42222. IOptionsSnapshot is currently a performance trap.
As nobody (famous last words) seems to care whether it is entirely recreated my question would be:
Why doesn't OptionsManager cache the result of an IOptionsMonitor.Get call? (leaving out the backwards compatibility part for the sake of argument)
Agreed that this implementation would have been more efficient. My only guess as to why it was done this way was because we had unified IOptions and IOptionsSnapsot implementations via the OptionsManager (though that's now changed in .NET 6).
The sad truth is that it would have been fixed if our own components were using it.
I'd be willing to take this change and see if there was any real impact not re-running factories per request. There are some very subtle differences but maybe worth the break.
cc @HaoK to see if he remembers why it was done this way.
The original idea was:
IOptions is singleton and cached forever
IOptionsSnapshot is supposed to be scoped and recomputed per request (which is fine for some things, that don't involve config) (mostly exists for backcompat)
IOptionsMonitor is supposed to combine the ability to have options updates with caching semantics, change notifications and cache eviction
If we are talking specifically about IOptionsSnapshot, that was intended to be really the no-caching you get a really new fresh instance on every scope, so it literally was intended to recompute everything on every request
Reacted by Oleksandr Borovenskyi and Marlon Eduardo Peña Llanos
Right. We should consider changing the implementation so that it caches the currently cached value so scoped services are a consistent view of the data but there's no need to recompute if nothing changes
Reacted by Martin Costello, Nate Barbettini, Tom Pažourek, Benjamin Stern, aelbatal-arabdt, Maximilian Haru Raditya, Brandon Gulrich, Christian Schneider, Ravindu Liyanapathirana, Juliano Leal Goncalves and 1 more
@davidfowl started work on it just now, practically the change is extremely simple * if * OptionsManager can take IOptionsMonitor instead of IOptionsFactory. This does mean an api compat error for the constructor, what's the policy on those? Alternatively I could duplicate the OptionsMonitor code into OptionsManager as that's as good as it gets with access to just IOptionsFactory.
This came up again today and to move this forward without breaking changes is to Iintroduce IOptionsMonitorSnapshot<T> that was what the original fix by @NinoFloris had. This new type would be scoped and would read the current value from IOptionsMonitor<T>. This solves the performance issues with IOptionsSnapshot because it doesn't do anything but cache the last value (which itself is cached and only changes when config changes).
The biggest performance challenge is the mixing IOptionSnapshot<T> with any expensive operation in IConfigureOptions<T>. The most common problem is running configuration binding per scope (usually per request in asp.net core). We want to cache the configuration that was bound until it changes, applying those cached values to the object. This is a difficult to do efficiently and would require codegen to make it fast (basically generating left hand right handcode to copy values):
classCachedConfigureFromConfiguration<T>(IConfigurationconfiguration):IConfigureOptions<T>whereT:class{privateT?_cached;publicvoidConfigure(Toptions){// Read the cached valuevarcache=_cached;if(cacheisnull){// If it's null, bind the configuration to a new instance and cache it_cached=Activator.CreateInstance<T>();ConfigurationBinder.Bind(configuration,_cached);cache=_cached;// Register a change callback to clear the cacheconfiguration.GetReloadToken().RegisterChangeCallback(static t =>{// Clear the cache when the configuration changes((CachedConfigureFromConfiguration<T>)t!)._cached=null;},this);}ApplyFromCached(cache,options);}privatevoidApplyFromCached(Tcache,Toptions){// Copy the cached options to the provided options instance// this would need to match the rules of what configuration binding would have done}}
Performance Comparison Between IOptionsSnapshot and IOptionsMonitor with Deep Cloning
We've obviously had a long discussion here. If I understand correctly, ensuring that each scope's configurations remain independent—allowing modifications in different scopes—makes it challenging to have caching. However, I want to raise something new here.
Issue:
In our distributed .NET application, using IOptionsSnapshot to handle complex configurations for each user (for A/B tests, so each request has a isolated settings and we overwrite them with different experiment config overwrites) has led to performance bottlenecks. Profiling revealed that configuration binding was consuming approximately 16% of the total CPU workload.
Key Observation:
Despite our assumption that IOptionsSnapshot's performance should be comparable to deserializing the configuration from a string for each request, this was not the case in fact. Simplified benchmark test results showed a 10x gap in cpu and memory allocations (see code at the bottom), and in our production environment with more complex configurations, the gap widened to over 100x.
Specifically, we benchmarked IOptionsSnapshot against a custom solution that used IOptionsMonitor and deep cloning of the configuration for each request (using serialization and deserialization, which is clearly not optimal and only for testing purposes):
Method
Mean
Error
StdDev
Gen0
Allocated
UseOptionsSnapshot
223.15 us
4.399 us
4.115 us
10.0098
123.78 KB
CloneOptionsMonitor
23.23 us
0.453 us
0.484 us
0.9155
11.49 KB
Solution:
We switched to using IOptionsMonitor, and performed deep cloning with a third-party library (DeepCloner). This reduced real CPU workload by 16% and memory allocation by 12%. The configuration-related CPU and memory allocation overheads were reduced by hundreds of times. The one line code change was as follows:
I believe these two lines are actually behave the same way, cloning and create a isolated scope level configuration which can be changed and will only have impacts inside the scope.
I understand the runtime lacks a generic deep clone implementation, but isn't the performance gap of IOptionsSnapshot so extreme? I believe there must be some room for improvement. If it's impossible, maybe we should just never use IOptionsSnapshot in any cases. The configuration builder bind methods are too expensive. Any thoughts on this?
Benchmark code:
using System.Text.Json;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace ConfigBenchmarks;
public class ComplexConfig
{
public string Name { get; set; }
public int Value { get; set; }
public List<SubConfig> SubConfigs { get; set; }
public Dictionary<string, NestedConfig> NestedConfigs { get; set; }
public List<ExtraNestedConfig> ExtraNestedConfigs { get; set; }
public ComplexConfig? Clone()
{
var json = JsonSerializer.Serialize(this);
return JsonSerializer.Deserialize<ComplexConfig>(json);
}
}
public class SubConfig
{
public string Key { get; set; }
public double Amount { get; set; }
public SubConfig? Clone()
{
var json = JsonSerializer.Serialize(this);
return JsonSerializer.Deserialize<SubConfig>(json);
}
}
public class NestedConfig
{
public Guid Id { get; set; }
public DateTime Timestamp { get; set; }
public List<string> Tags { get; set; }
public Dictionary<string, int> AdditionalData { get; set; }
public NestedConfig? Clone()
{
var json = JsonSerializer.Serialize(this);
return JsonSerializer.Deserialize<NestedConfig>(json);
}
}
public class ExtraNestedConfig
{
public string Category { get; set; }
public List<NestedConfig> NestedItems { get; set; }
public SubConfig DefaultSubConfig { get; set; }
public ExtraNestedConfig? Clone()
{
var json = JsonSerializer.Serialize(this);
return JsonSerializer.Deserialize<ExtraNestedConfig>(json);
}
}
[MemoryDiagnoser]
public class ConfigPerformanceBenchmark
{
private IServiceProvider _serviceProvider;
private IConfiguration _configuration;
private IOptionsMonitor<ComplexConfig> _optionsMonitor;
[GlobalSetup]
public void Setup()
{
var configDictionary = new Dictionary<string, string>
{
["Name"] = "TestConfig",
["Value"] = "42",
["SubConfigs:0:Key"] = "SubKey1",
["SubConfigs:0:Amount"] = "10.5",
["SubConfigs:1:Key"] = "SubKey2",
["SubConfigs:1:Amount"] = "20.7",
["NestedConfigs:Nested1:Id"] = Guid.NewGuid().ToString(),
["NestedConfigs:Nested1:Timestamp"] = DateTime.Now.ToString("o"),
["NestedConfigs:Nested1:Tags:0"] = "Tag1",
["NestedConfigs:Nested1:Tags:1"] = "Tag2",
["NestedConfigs:Nested2:Id"] = Guid.NewGuid().ToString(),
["NestedConfigs:Nested2:Timestamp"] = DateTime.Now.AddDays(1).ToString("o"),
["NestedConfigs:Nested2:Tags:0"] = "Tag3",
["NestedConfigs:Nested2:Tags:1"] = "Tag4",
["SubConfigs:2:Key"] = "SubKey3",
["SubConfigs:2:Amount"] = "30.9",
["SubConfigs:2:Key"] = "SubKey3",
["SubConfigs:2:Amount"] = "30.9",
["SubConfigs:3:Key"] = "SubKey4",
["SubConfigs:3:Amount"] = "40.1",
["NestedConfigs:Nested3:Id"] = Guid.NewGuid().ToString(),
["NestedConfigs:Nested3:Timestamp"] = DateTime.Now.AddDays(2).ToString("o"),
["NestedConfigs:Nested3:Tags:0"] = "Tag5",
["NestedConfigs:Nested3:Tags:1"] = "Tag6",
["NestedConfigs:Nested3:AdditionalData:Key1"] = "100",
["NestedConfigs:Nested3:AdditionalData:Key2"] = "200",
["NestedConfigs:Nested4:Id"] = Guid.NewGuid().ToString(),
["NestedConfigs:Nested4:Timestamp"] = DateTime.Now.AddDays(3).ToString("o"),
["NestedConfigs:Nested4:Tags:0"] = "Tag7",
["NestedConfigs:Nested4:Tags:1"] = "Tag8",
["NestedConfigs:Nested4:AdditionalData:Key1"] = "300",
["NestedConfigs:Nested4:AdditionalData:Key2"] = "400",
["ExtraNestedConfigs:0:Category"] = "CategoryA",
["ExtraNestedConfigs:0:NestedItems:0:Id"] = Guid.NewGuid().ToString(),
["ExtraNestedConfigs:0:NestedItems:0:Timestamp"] = DateTime.Now.ToString("o"),
["ExtraNestedConfigs:0:NestedItems:0:Tags:0"] = "Tag1",
["ExtraNestedConfigs:0:NestedItems:0:Tags:1"] = "Tag2",
["ExtraNestedConfigs:0:NestedItems:0:AdditionalData:Key1"] = "100",
["ExtraNestedConfigs:0:NestedItems:0:AdditionalData:Key2"] = "200",
["ExtraNestedConfigs:0:DefaultSubConfig:Key"] = "DefaultKey1",
["ExtraNestedConfigs:0:DefaultSubConfig:Amount"] = "10.5",
["ExtraNestedConfigs:1:Category"] = "CategoryB",
["ExtraNestedConfigs:1:NestedItems:0:Id"] = Guid.NewGuid().ToString(),
["ExtraNestedConfigs:1:NestedItems:0:Timestamp"] = DateTime.Now.AddDays(1).ToString("o"),
["ExtraNestedConfigs:1:NestedItems:0:Tags:0"] = "Tag3",
["ExtraNestedConfigs:1:NestedItems:0:Tags:1"] = "Tag4",
["ExtraNestedConfigs:1:NestedItems:0:AdditionalData:Key1"] = "300",
["ExtraNestedConfigs:1:NestedItems:0:AdditionalData:Key2"] = "400",
["ExtraNestedConfigs:1:DefaultSubConfig:Key"] = "DefaultKey2",
["ExtraNestedConfigs:1:DefaultSubConfig:Amount"] = "20.7",
["ExtraNestedConfigs:2:Category"] = "CategoryC",
["ExtraNestedConfigs:2:NestedItems:0:Id"] = Guid.NewGuid().ToString(),
["ExtraNestedConfigs:2:NestedItems:0:Timestamp"] = DateTime.Now.AddDays(2).ToString("o"),
["ExtraNestedConfigs:2:NestedItems:0:Tags:0"] = "Tag5",
["ExtraNestedConfigs:2:NestedItems:0:Tags:1"] = "Tag6",
["ExtraNestedConfigs:2:NestedItems:0:AdditionalData:Key1"] = "500",
["ExtraNestedConfigs:2:NestedItems:0:AdditionalData:Key2"] = "600",
["ExtraNestedConfigs:2:DefaultSubConfig:Key"] = "DefaultKey3",
["ExtraNestedConfigs:2:DefaultSubConfig:Amount"] = "30.9",
["ExtraNestedConfigs:3:Category"] = "CategoryD",
["ExtraNestedConfigs:3:NestedItems:0:Id"] = Guid.NewGuid().ToString(),
["ExtraNestedConfigs:3:NestedItems:0:Timestamp"] = DateTime.Now.AddDays(3).ToString("o"),
["ExtraNestedConfigs:3:NestedItems:0:Tags:0"] = "Tag7",
["ExtraNestedConfigs:3:NestedItems:0:Tags:1"] = "Tag8",
["ExtraNestedConfigs:3:NestedItems:0:AdditionalData:Key1"] = "700",
["ExtraNestedConfigs:3:NestedItems:0:AdditionalData:Key2"] = "800",
["ExtraNestedConfigs:3:DefaultSubConfig:Key"] = "DefaultKey4",
["ExtraNestedConfigs:3:DefaultSubConfig:Amount"] = "40.1"
};
_configuration = new ConfigurationBuilder()
.AddInMemoryCollection(configDictionary)
.Build();
var services = new ServiceCollection();
services.AddOptions();
services.Configure<ComplexConfig>(config => { _configuration.Bind(config); });
_serviceProvider = services.BuildServiceProvider();
_optionsMonitor = _serviceProvider.GetRequiredService<IOptionsMonitor<ComplexConfig>>();
}
[Benchmark]
public int UseOptionsSnapshot()
{
using var scope = _serviceProvider.CreateScope();
var snapshot = scope.ServiceProvider.GetRequiredService<IOptionsSnapshot<ComplexConfig>>();
return snapshot.Value.GetHashCode();
}
[Benchmark]
public int CloneOptionsMonitor()
{
using var scope = _serviceProvider.CreateScope();
return _optionsMonitor.CurrentValue.Clone()!.GetHashCode() + scope.GetHashCode();
}
}
public static class Program
{
public static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<ConfigPerformanceBenchmark>();
}
}
Profiling revealed that configuration binding was consuming approximately 16% of the total CPU workload.
I'm curious if you tried using the configuration binder source generator? What impact would it have on your scenario? It should make configuration binding much faster since it doesn't use reflection, and instead sets the object's properties directly via generated code.
Profiling revealed that configuration binding was consuming approximately 16% of the total CPU workload.
I'm curious if you tried using the configuration binder source generator? What impact would it have on your scenario? It should make configuration binding much faster since it doesn't use reflection, and instead sets the object's properties directly via generated code.
The ConfigurationBinderSourceGenerator seems really cool! Unfortunately, this service is still using .NET 6 due to some issues that arose during our recent upgrade to .NET 8, so I'm unable to test the actual difference in a production environment. But I can see from the benchmark above that it consumes only half the CPU compared to the previous approach. While it's not yet the default in .NET 8, I think that code gen sounds one right direction for optimization.
Method
Mean
Error
StdDev
Gen0
Allocated
UseOptionsSnapshot
216.80 us
2.850 us
5.757 us
0.2441
121.05 KB
UseOptionsSnapshotWithCodeGen
112.15 us
1.426 us
3.131 us
-
69.35 KB
CloneOptionsMonitor
22.83 us
0.334 us
0.279 us
0.0305
11.34 KB
However, it's only 50% improvement. When the configs are more complex [example], the performance difference could still be very large. As mentioned earlier, even cloning using JsonSerializer for serialization and deserialization provides dozens of times the performance improvement.
However, when the configs become more complex [example], the performance difference consistently remains around 2x, regardless of the complexity.
That example you used for the benchmark seems quite extreme in terms of complexity. Do you mind me asking what exactly are you modelling in the real application that requires such deep configuration structure with that many elements? I know this doesn't solve the slowdown or anything, just curious as I don't think I've ever needed such elaborate options object graph before. I wonder if your design is flawed here to be honest.
However, when the configs become more complex [example], the performance difference consistently remains around 2x, regardless of the complexity.
That example you used for the benchmark seems quite extreme in terms of complexity. Do you mind me asking what exactly are you modelling in the real application that requires such deep configuration structure with that many elements? I know this doesn't solve the slowdown or anything, just curious as I don't think I've ever needed such elaborate options object graph before. I wonder if your design is flawed here to be honest.
I don't think it's out of the ordinary to have some pretty complicated configuration files. It's common to utilize several configuration sources. And Microsoft encourages usage of configuration for more than just IOptions.
In our production environment, the configuration isn’t as large as in the example above. The significant optimization in production (> 100x) is due to the absence of Config Code Gen by default, the fact that the service still uses .NET 6, and our use of DeepCloner instead of serialization and deserialization (which can be much faster in many common cases). Btw, the example above has thousands of lines, which may be rare, but it is not "deep" (only 3-4 levels).
I can provide a simpler example to show the issue (with enabled config code gen). Consider a configuration containing only int properties, without any custom types. Below are the benchmark results for configurations with 1,000 int properties and 100 int properties.
In this case, the performance difference between configuration binding with code gen and json serialization isn't significant. However, json serialization is not well-suited for deep cloning. Using real deep cloning shows a performance improvement of hundreds of times. I think maybe we can use code gen to do the deep clone for us.
IOptionsSnapshot exists to provide a per-scope view that re-runs the full configure pipeline (IConfigureOptions, IPostConfigureOptions, IValidateOptions) on each scope. That contract is what makes it valid for any of those callbacks to depend on scoped, mutable state. The cost measured here is therefore the cost of honouring that contract, not a framework inefficiency.
If you, as the application author, know your pipeline is stateless (no configure callback depends on anything scope-specific or otherwise non-deterministic), then you do not need IOptionsSnapshot. Inject IOptionsMonitor and either use CurrentValue directly or capture it in a context or register in DI like this:
If you cannot make that statement about your pipeline, then neither can the framework, and it has no choice but to run it from scratch. Moreover, there is effectively no room for caching, because caching requires the result to be a deterministic function of its inputs, and stateful callbacks break that assumption.
This leaves a narrow use case where an application depends on a scoped configuration pipeline and has an options graph large and deep enough to create a measurable problem. That intersection is uncommon and highly context-specific. The realistic options are:
Accept the CPU and allocation cost, as it is the direct cost of the required behaviour.
Reshape the design so that the scope-dependent part of the configuration is small (a narrow options type bound per scope), while the majority is a stateless snapshot resolved via IOptionsMonitor.
Implement a custom IOptionsSnapshot with optimisations enabled by domain knowledge and execution context, such as domain-specific deep cloning, partial rebind, or targeted caching and memoisation.
None of these can be done by a general-purpose framework without either breaking the contract or guessing semantics it cannot observe.
Source generators (configuration binding, options validation) reduce part of the overhead by removing reflection from the per-scope work, and we will continue to improve them. However, they do not, and cannot, eliminate the inherent per-scope cost of IOptionsSnapshot itself.
Closing as by design. If you encounter a concrete, reproducible case that does not fall into the “stateful configure pipeline plus large options graph” category described above, please open a focused issue with a repro and we will take another look.
Even if "as designed" and "not planned" this should become a major part of the documentation as it's a non obvious side effect of using the highly encouraged IOptionsSnapshot pattern.
At the very least, this should become a documentation chore to point out this specific design choice.
Yes the important bit is that a scope will often be as small as a web request. In that context it seems obvious that better documentation around IOptionsSnapshot should exist. It's essentially unfit to be used in ASP.NET based apps, beyond the simplest option instances.
Documentation issues belong in another repository, I've created an issue there to add a note about the performance ramifications and the options users have to retain performance (please see dotnet/docs#53890).
Activity
davidfowl commentedon Jun 6, 2021
Yes this is a known issue #42222. IOptionsSnapshot is currently a performance trap.
Agreed that this implementation would have been more efficient. My only guess as to why it was done this way was because we had unified IOptions and IOptionsSnapsot implementations via the OptionsManager (though that's now changed in .NET 6).
The sad truth is that it would have been fixed if our own components were using it.
I'd be willing to take this change and see if there was any real impact not re-running factories per request. There are some very subtle differences but maybe worth the break.
cc @HaoK to see if he remembers why it was done this way.
HaoK commentedon Jun 6, 2021
The original idea was:
IOptions is singleton and cached forever
IOptionsSnapshot is supposed to be scoped and recomputed per request (which is fine for some things, that don't involve config) (mostly exists for backcompat)
IOptionsMonitor is supposed to combine the ability to have options updates with caching semantics, change notifications and cache eviction
HaoK commentedon Jun 7, 2021
If we are talking specifically about IOptionsSnapshot, that was intended to be really the no-caching you get a really new fresh instance on every scope, so it literally was intended to recompute everything on every request
davidfowl commentedon Jun 7, 2021
Right. We should consider changing the implementation so that it caches the currently cached value so scoped services are a consistent view of the data but there's no need to recompute if nothing changes
NinoFloris commentedon Jul 15, 2021
@davidfowl I see it's been placed in 7.0 is a PR for 6.0 still welcome?
davidfowl commentedon Jul 15, 2021
Yes, if you send a PR, it can be done without adding public API (I believe).
NinoFloris commentedon Jul 15, 2021
I agree, alright will be cooking it up.
NinoFloris commentedon Jul 16, 2021
@davidfowl started work on it just now, practically the change is extremely simple * if * OptionsManager can take IOptionsMonitor instead of IOptionsFactory. This does mean an api compat error for the constructor, what's the policy on those? Alternatively I could duplicate the OptionsMonitor code into OptionsManager as that's as good as it gets with access to just IOptionsFactory.
runtime/src/libraries/Microsoft.Extensions.Options/src/OptionsManager.cs
Lines 17 to 27 in 57bfe47
Ideally I'd also inline that silly cache (which is only used in OptionsManager) but it's a public type so I guess that's a no ;)
davidfowl commentedon Jul 16, 2021
Or just make a new internal type so we don't need to change the public surface here. Call it OptionsSnapshot<T>
37 remaining items
davidfowl commentedon May 16, 2024
This came up again today and to move this forward without breaking changes is to Iintroduce IOptionsMonitorSnapshot<T> that was what the original fix by @NinoFloris had. This new type would be scoped and would read the current value from
IOptionsMonitor<T>. This solves the performance issues with IOptionsSnapshot because it doesn't do anything but cache the last value (which itself is cached and only changes when config changes).The biggest performance challenge is the mixing
IOptionSnapshot<T>with any expensive operation inIConfigureOptions<T>. The most common problem is running configuration binding per scope (usually per request in asp.net core). We want to cache the configuration that was bound until it changes, applying those cached values to the object. This is a difficult to do efficiently and would require codegen to make it fast (basically generating left hand right handcode to copy values):WAcry commentedon Aug 30, 2024
Performance Comparison Between IOptionsSnapshot and IOptionsMonitor with Deep Cloning
We've obviously had a long discussion here. If I understand correctly, ensuring that each scope's configurations remain independent—allowing modifications in different scopes—makes it challenging to have caching. However, I want to raise something new here.
Issue:
In our distributed .NET application, using
IOptionsSnapshotto handle complex configurations for each user (for A/B tests, so each request has a isolated settings and we overwrite them with different experiment config overwrites) has led to performance bottlenecks. Profiling revealed that configuration binding was consuming approximately 16% of the total CPU workload.Key Observation:
Despite our assumption that
IOptionsSnapshot's performance should be comparable to deserializing the configuration from a string for each request, this was not the case in fact. Simplified benchmark test results showed a 10x gap in cpu and memory allocations (see code at the bottom), and in our production environment with more complex configurations, the gap widened to over 100x.Specifically, we benchmarked
IOptionsSnapshotagainst a custom solution that usedIOptionsMonitorand deep cloning of the configuration for each request (using serialization and deserialization, which is clearly not optimal and only for testing purposes):Solution:
We switched to using
IOptionsMonitor, and performed deep cloning with a third-party library (DeepCloner). This reduced real CPU workload by 16% and memory allocation by 12%. The configuration-related CPU and memory allocation overheads were reduced by hundreds of times. The one line code change was as follows:I believe these two lines are actually behave the same way, cloning and create a isolated scope level configuration which can be changed and will only have impacts inside the scope.
I understand the runtime lacks a generic deep clone implementation, but isn't the performance gap of IOptionsSnapshot so extreme? I believe there must be some room for improvement. If it's impossible, maybe we should just never use IOptionsSnapshot in any cases. The configuration builder bind methods are too expensive. Any thoughts on this?
Benchmark code:
eerhardt commentedon Aug 30, 2024
I'm curious if you tried using the configuration binder source generator? What impact would it have on your scenario? It should make configuration binding much faster since it doesn't use reflection, and instead sets the object's properties directly via generated code.
WAcry commentedon Aug 31, 2024
The
ConfigurationBinderSourceGeneratorseems really cool! Unfortunately, this service is still using .NET 6 due to some issues that arose during our recent upgrade to .NET 8, so I'm unable to test the actual difference in a production environment. But I can see from the benchmark above that it consumes only half the CPU compared to the previous approach. While it's not yet the default in .NET 8, I think that code gen sounds one right direction for optimization.However, it's only 50% improvement. When the configs are more complex [example], the performance difference could still be very large. As mentioned earlier, even cloning using JsonSerializer for serialization and deserialization provides dozens of times the performance improvement.
julealgon commentedon Sep 2, 2024
@WAcry
That example you used for the benchmark seems quite extreme in terms of complexity. Do you mind me asking what exactly are you modelling in the real application that requires such deep configuration structure with that many elements? I know this doesn't solve the slowdown or anything, just curious as I don't think I've ever needed such elaborate options object graph before. I wonder if your design is flawed here to be honest.
profet23 commentedon Sep 2, 2024
I don't think it's out of the ordinary to have some pretty complicated configuration files. It's common to utilize several configuration sources. And Microsoft encourages usage of configuration for more than just IOptions.
For instance Microsoft feature management (feature flags) relies on it:
https://learn.microsoft.com/en-us/azure/azure-app-configuration/feature-management-dotnet-reference
WAcry commentedon Sep 2, 2024
In our production environment, the configuration isn’t as large as in the example above. The significant optimization in production (> 100x) is due to the absence of Config Code Gen by default, the fact that the service still uses .NET 6, and our use of DeepCloner instead of serialization and deserialization (which can be much faster in many common cases). Btw, the example above has thousands of lines, which may be rare, but it is not "deep" (only 3-4 levels).
I can provide a simpler example to show the issue (with enabled config code gen). Consider a configuration containing only int properties, without any custom types. Below are the benchmark results for configurations with 1,000 int properties and 100 int properties.
In this case, the performance difference between configuration binding with code gen and json serialization isn't significant. However, json serialization is not well-suited for deep cloning. Using real deep cloning shows a performance improvement of hundreds of times. I think maybe we can use code gen to do the deep clone for us.
rosebyte commentedon Mar 17, 2026
Triage: we may investigate if there is anything left after source generators.
rosebyte commentedon May 19, 2026
IOptionsSnapshot exists to provide a per-scope view that re-runs the full configure pipeline (IConfigureOptions, IPostConfigureOptions, IValidateOptions) on each scope. That contract is what makes it valid for any of those callbacks to depend on scoped, mutable state. The cost measured here is therefore the cost of honouring that contract, not a framework inefficiency.
If you, as the application author, know your pipeline is stateless (no configure callback depends on anything scope-specific or otherwise non-deterministic), then you do not need IOptionsSnapshot. Inject IOptionsMonitor and either use CurrentValue directly or capture it in a context or register in DI like this:
If you cannot make that statement about your pipeline, then neither can the framework, and it has no choice but to run it from scratch. Moreover, there is effectively no room for caching, because caching requires the result to be a deterministic function of its inputs, and stateful callbacks break that assumption.
This leaves a narrow use case where an application depends on a scoped configuration pipeline and has an options graph large and deep enough to create a measurable problem. That intersection is uncommon and highly context-specific. The realistic options are:
None of these can be done by a general-purpose framework without either breaking the contract or guessing semantics it cannot observe.
Source generators (configuration binding, options validation) reduce part of the overhead by removing reflection from the per-scope work, and we will continue to improve them. However, they do not, and cannot, eliminate the inherent per-scope cost of IOptionsSnapshot itself.
Closing as by design. If you encounter a concrete, reproducible case that does not fall into the “stateful configure pipeline plus large options graph” category described above, please open a focused issue with a repro and we will take another look.
profet23 commentedon May 19, 2026
Even if "as designed" and "not planned" this should become a major part of the documentation as it's a non obvious side effect of using the highly encouraged IOptionsSnapshot pattern.
At the very least, this should become a documentation chore to point out this specific design choice.
NinoFloris commentedon May 19, 2026
Yes the important bit is that a scope will often be as small as a web request. In that context it seems obvious that better documentation around IOptionsSnapshot should exist. It's essentially unfit to be used in ASP.NET based apps, beyond the simplest option instances.
profet23 commentedon May 19, 2026
@rosebyte / @davidfowl please consider reopening this issue as a documentation chore.
rosebyte commentedon May 20, 2026
Documentation issues belong in another repository, I've created an issue there to add a note about the performance ramifications and the options users have to retain performance (please see dotnet/docs#53890).