Skip to content

Reduce UserManager construction cost - #70222

Closed
davidfowl wants to merge 2 commits into
mainfrom
perf/identity-usermanager-ctor
Closed

davidfowl wants to merge 2 commits into
mainfrom
perf/identity-usermanager-ctor

Conversation

@davidfowl

@davidfowl davidfowl commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Reduce UserManager construction cost

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making.

Reduce allocations and work when constructing UserManager<TUser>

Description

Make UserManager<TUser> cheaper to construct. It's scoped and gets constructed on every request that resolves SignInManager/ISecurityStampValidator, which includes every cookie-authenticated request through SecurityStampValidator.ValidatePrincipalAsync.

  • The injected UserValidators and PasswordValidators are added with one AddRange into lists whose capacity is set to the collection count, which is known when DI injects an array. Before, a foreach over IEnumerable<T> boxed an enumerator and grew each list to the default capacity of 4 through Add. The lists are still created by field initializers, so they exist before the constructor's virtual Logger setter runs.
  • The token ProviderMap is enumerated once as key/value pairs. Before, the code enumerated Keys and then looked each key up with the indexer.

There is no behavior change. Validator order, contents, mutability (IList<T> backed by List<T>), the null-collection handling and token provider registration order are all unchanged. There are no public API changes.

Benchmark

Local BenchmarkDotNet run (MemoryDiagnoser, in-process). The baseline and PR builds of Microsoft.Extensions.Identity.Core.dll ran in separate shared-framework copies, interleaved A, B, A, B over 3 rounds. The benchmark resolves the service in a new DI scope with AddIdentityCore<User>().AddSignInManager().AddDefaultTokenProviders(), a no-op store and AddLogging().

Method Round main Mean PR Mean main Alloc PR Alloc
Resolve UserManager<TUser> 1 1.780 us 1.667 us 4.23 KB 4.13 KB
Resolve UserManager<TUser> 2 1.781 us 1.694 us 4.23 KB 4.13 KB
Resolve UserManager<TUser> 3 1.803 us 1.782 us 4.23 KB 4.13 KB
Resolve ISecurityStampValidator 1 2.911 us 2.855 us 5.68 KB 5.57 KB
Resolve ISecurityStampValidator 2 2.876 us 2.887 us 5.68 KB 5.57 KB
Resolve ISecurityStampValidator 3 2.834 us 2.857 us 5.68 KB 5.57 KB

Every resolve that constructs a UserManager allocates about 104 B less. UserManager resolve time was about 5% lower in two rounds and about 1% lower in the third. The ISecurityStampValidator resolve times are within noise; only its allocation goes down. In an isolated benchmark of the token provider loop with 4 default providers, the loop alone took 56.1 ns on main and 34.5 ns with this PR.

This complements #70174, which caches the metrics objects, and #70175, which caches the logger. Those PRs touch different lines, and this one does not overlap them.

Tests

I added UserManagerTest.ConstructorCopiesValidatorsInOrderAndCollectionsAreAvailableToVirtualMembers, which covers validator order, mutability, null inputs and a derived Logger setter that reads the collections. With the final commit, the UserManager, SignInManager, SecurityStamp and claims factory tests pass: 208 passed, 1 skipped. On the first commit, the full Microsoft.AspNetCore.Identity.Test run had 565 passed and 1 skipped. The 16 failures were all IdentityUIScriptsTest CDN tests (*_Matches_CDNContent, *_SubresourceIntegrityCheck), which need outbound internet access that isn't available in the environment where I ran them. They don't involve this change.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Build the validator lists at their final size and enumerate the token
provider map once instead of re-looking each key up.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 1, 2026 15:11
@github-actions github-actions Bot added the area-identity Includes: Identity and providers label Nov 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Validator collections are now null when the constructor invokes the virtual Logger setter, causing derived setters that access them to throw NullReferenceException during construction.

1 open issue
What changed in this PR

Reduces per-scope UserManager<TUser> construction overhead in Identity, complementing the metrics and logger caching changes in #70174 and #70175.

Changes:

  • Constructs validator lists directly from injected collections instead of adding items individually.
  • Enumerates token provider key/value pairs to avoid separate dictionary lookups.
File Description
src/​Identity/​Extensions.Core/​src/​UserManager.cs Optimizes validator collection initialization and token provider enumeration.

Review effort: Balanced

Initialize the lists in field initializers and bulk-add the injected
validators with an exact capacity, so derived Logger setters still see
non-null collections.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Nov 13, 2026
@davidfowl

Copy link
Copy Markdown
Member Author

Tiny gain

@davidfowl davidfowl closed this Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-identity Includes: Identity and providers pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants