Skip to content

Avoid ViewLocationExpanderContext allocations on Razor view lookup cache hits - #70211

Closed
davidfowl wants to merge 2 commits into
mainfrom
perf/mvc-viewengine-expander-context
Closed

davidfowl wants to merge 2 commits into
mainfrom
perf/mvc-viewengine-expander-context

Conversation

@davidfowl

Copy link
Copy Markdown
Member

Summary

RazorViewEngine.LocatePageFromViewLocations runs for every view, partial, layout and _ViewStart lookup. Before this change, every lookup allocated a ViewLocationExpanderContext and a Dictionary<string, string?> for expander values, even on a cache hit, so that the expanders could populate values for the cache key.

The default RazorPages registration adds PageViewLocationExpander, whose PopulateValues does nothing. With this change:

  • An internal marker interface, IViewLocationExpanderWithoutValues, identifies expanders that never populate values.
  • PageViewLocationExpander implements the marker only when GetType() == typeof(PageViewLocationExpander). A subclass might override PopulateValues, so subclasses keep the old behavior.
  • When every registered expander declares that it populates no values, the cache key is built without the always-empty values dictionary. The expander context, including its values dictionary passed to ExpandViewLocations, is then created only on a cache miss.
  • If any other expander is registered (user, localization or similar), the existing code path is used unchanged.

There are no public API changes. ViewLocationCacheKey is internal, so the change in its key contents is not observable.

Benchmark

ViewEngineBenchmark.FindPartial: a cache-hit partial lookup with AddMvc() defaults, which include PageViewLocationExpander. Three interleaved A/B rounds with BenchmarkDotNet:

Round main PR main alloc PR alloc
1 194.7 ns 194.1 ns 856 B 704 B
2 204.9 ns 178.6 ns 856 B 704 B
3 202.1 ns 204.2 ns 856 B 704 B

That is −152 B (−18%) per view, partial or layout lookup. Time is flat to about −5%, within the noise. A typical page render does several lookups (view, layout and each partial), so the saving repeats on each one.

Tests

  • New RazorViewEngineTest tests:
    • Valueless expanders are not asked to populate values and still expand locations on a miss.
    • A mix of a valueless expander and a normal expander still populates values.
  • New PageViewLocationExpanderTest test: the marker is true only for the exact type, not for derived types.
  • Results: Mvc.Razor.Test 362 passed, Mvc.RazorPages.Test 772 passed, Mvc.FunctionalTests 1694 passed.

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

When every registered view location expander is known not to populate
values (the default PageViewLocationExpander), the expander values are
not part of the cache key, so the expander context and its values
dictionary are only created on a cache miss.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 1, 2026 09:20
@github-actions github-actions Bot added the area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates 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

The change introduces a cross-assembly dependency on an internal Mvc.Razor type via a friend-assembly grant, requiring an assembly-local implementation or a supported public contract.

1 open issue
What changed in this PR

This PR reduces allocations during Razor view-location cache hits by deferring expander context creation when no registered expander contributes cache-key values.

Changes:

  • Adds an internal capability marker and opts in the exact PageViewLocationExpander type.
  • Defers context allocation until a cache miss while preserving value population for other expanders.
  • Adds targeted tests and a warmed-cache partial-view benchmark.
File Description
src/​Mvc/​perf/​Microbenchmarks/​Microsoft.AspNetCore.Mvc/​ViewEngineBenchmark.cs Benchmarks cached partial-view lookups with default MVC services.
src/​Mvc/​perf/​Microbenchmarks/​Microsoft.AspNetCore.Mvc.Views/​Views/​Shared/​_ViewEngineBenchmarkPartial.cshtml Supplies the benchmark’s partial view.
src/​Mvc/​Mvc.RazorPages/​test/​Infrastructure/​PageViewLocationExpanderTest.cs Tests exact-type opt-in and derived-type exclusion.
src/​Mvc/​Mvc.RazorPages/​src/​Infrastructure/​PageViewLocationExpander.cs Declares the exact type as contributing no expander values.
src/​Mvc/​Mvc.Razor/​test/​RazorViewEngineTest.cs Tests valueless and mixed-expander cache behavior.
src/​Mvc/​Mvc.Razor/​src/​RazorViewEngine.cs Defers context creation for eligible cache lookups.
src/​Mvc/​Mvc.Razor/​src/​IViewLocationExpanderWithoutValues.cs Defines the internal capability contract.

Review effort: Balanced

/// An <see cref="IViewLocationExpander"/> for PageView.
/// </summary>
public class PageViewLocationExpander : IViewLocationExpander
public class PageViewLocationExpander : IViewLocationExpander, IViewLocationExpanderWithoutValues

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for the review. I looked into restructuring this, but I'd like to keep the current shape, for these reasons:

  1. The pattern already ships between these two assemblies. Mvc.Razor defines internal interface IModelTypeProvider (src/Mvc/Mvc.Razor/src/IModelTypeProvider.cs). The public RazorPages type RazorPageAdapter implements it (src/Mvc/Mvc.RazorPages/src/Infrastructure/RazorPageAdapter.cs:15), and RazorPageActivator.cs:71 type-tests for it. This PR uses the same pattern: an internal capability interface in Mvc.Razor, implemented explicitly by a public RazorPages type and type-tested by Mvc.Razor. Mvc.RazorPages also already uses internal Mvc.Razor types RazorPagePropertyActivator, ViewPath and RazorFileHierarchy through the same InternalsVisibleTo grant.
  2. There is no version-skew risk. Both projects are IsAspNetCoreApp=true / IsPackable=false and ship only together in Microsoft.AspNetCore.App (eng/SharedFramework.Local.props:89-90).
  3. The optimization can't stay inside one assembly without losing the win. PageViewLocationExpander lives in RazorPages, and Mvc.Razor can't reference RazorPages. Without a marker, RazorViewEngine must assume that any registered expander populates values, which is exactly the case AddMvc and AddRazorPages hit. Keeping the logic in Mvc.Razor alone would only help apps with zero expanders and would drop most of the 152 B per lookup. A public capability contract would mean a new public API (and an API proposal) for a framework-internal optimization, which this PR deliberately avoids.

The marker is behavior-safe: it applies only when GetType() == typeof(PageViewLocationExpander), so a subclass that overrides PopulateValues keeps the existing path (covered by DoesNotPopulateValues_TrueOnlyForExactType).

I'm leaving this thread open for a maintainer to decide. If you'd prefer the in-assembly-only version (or a different internal mechanism), I'm happy to change it.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for flagging this. This PR is being closed because the approach relies on a new cross-assembly internal (InternalsVisibleTo) dependency, which the repo's copilot-instructions forbid, and a version without it showed no measurable gain.

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

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

Copy link
Copy Markdown
Member Author

Closing this PR. The win depends on a new internal interface in Mvc.Razor that Mvc.RazorPages implements through InternalsVisibleTo, and the repo's copilot-instructions forbid adding new cross-assembly internal dependencies. A version without that dependency showed no measurable gain (about 201–210 ns and 856 B for both the baseline and the variant), because AddMvc always registers PageViewLocationExpander. Thanks to everyone who reviewed.

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

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

Labels

area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants