Skip to content

Commit

Permalink
Improve performance of IsRootScope check
Browse files Browse the repository at this point in the history
- Stash a field instead of doing an equality comparison.

Fixes #54351
  • Loading branch information
davidfowl committed Jun 22, 2021
1 parent 183c4d1 commit 887a3a9
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ internal sealed class ServiceProviderEngineScope : IServiceScope, IServiceProvid
private bool _disposed;
private List<object> _disposables;

public ServiceProviderEngineScope(ServiceProvider provider)
public ServiceProviderEngineScope(ServiceProvider provider, bool isRootScope)
{
ResolvedServices = new Dictionary<ServiceCacheKey, object>();
RootProvider = provider;
IsRootScope = isRootScope;
}

internal Dictionary<ServiceCacheKey, object> ResolvedServices { get; }
Expand All @@ -29,7 +30,7 @@ public ServiceProviderEngineScope(ServiceProvider provider)
// For other scopes, it protects ResolvedServices and the list of disposables
internal object Sync => ResolvedServices;

public bool IsRootScope => this == RootProvider.Root;
public bool IsRootScope { get; }

internal ServiceProvider RootProvider { get; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ internal ServiceProvider(IEnumerable<ServiceDescriptor> serviceDescriptors, Serv
_createServiceAccessor = CreateServiceAccessor;
_realizedServices = new ConcurrentDictionary<Type, Func<ServiceProviderEngineScope, object>>();

Root = new ServiceProviderEngineScope(this);
Root = new ServiceProviderEngineScope(this, isRootScope: true);
CallSiteFactory = new CallSiteFactory(serviceDescriptors);
// The list of built in services that aren't part of the list of service descriptors
// keep this in sync with CallSiteFactory.IsService
Expand Down Expand Up @@ -173,7 +173,7 @@ internal IServiceScope CreateScope()
ThrowHelper.ThrowObjectDisposedException();
}

return new ServiceProviderEngineScope(this);
return new ServiceProviderEngineScope(this, isRootScope: false);
}

private ServiceProviderEngine GetEngine()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class ServiceProviderEngineScopeTests
public void DoubleDisposeWorks()
{
var provider = new ServiceProvider(new ServiceCollection(), ServiceProviderOptions.Default);
var serviceProviderEngineScope = new ServiceProviderEngineScope(provider);
var serviceProviderEngineScope = new ServiceProviderEngineScope(provider, isRootScope: true);
serviceProviderEngineScope.ResolvedServices.Add(new ServiceCacheKey(typeof(IFakeService), 0), null);
serviceProviderEngineScope.Dispose();
serviceProviderEngineScope.Dispose();
Expand Down

0 comments on commit 887a3a9

Please sign in to comment.