Skip to content

Reduce allocations in Graphics parsing - #40776

Merged
kubaflo merged 3 commits into
mainfrom
simonrozsival-graphics-parsing-performance
Nov 30, 2026
Merged

kubaflo merged 3 commits into
mainfrom
simonrozsival-graphics-parsing-performance

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 72c2b3e58cc1c96d785c1d258d1a3cb080ba37ec

Dimension Assessment Rationale
Change confidence 7.5/10 ↑ Graphics-only patch remains byte-for-byte identical after rebasing onto the finalized prerequisite; no conflicts.
↑ Build and full Graphics.Tests passed on this exact head: 476/476 on net12.0 with platform TFMs disabled.
↑ Inherited report: 300,000 generated paths matched old vs new; not reproduced here.
↓ Public ParseFloat(null) exception type changes; malformed-path nontermination remains.
↓ Benchmarks and external netstandard compatibility not revalidated; CI results have not been evaluated.

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Target Branch

This PR is for Initial base
New features, API changes, or .NET 12 work (including .NET 12 fixes) main
.NET 11 servicing fixes net11, for review
Older servicing, release integration, infrastructure, or documentation The branch designated for that work

For .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into net11; agents must not retarget or merge.

This is next-major (.NET 12) work stacked on #40775 (simonrozsival-modern-framework-prerequisite, final head 8c97daa2f6953333e3773e2366f67180d368ff2a). The stack now includes current main (0806e8de4c) with #40608 merged. The current snapshot builds Graphics.Tests for net12.0; the intended eventual integration target is main. The PR base and GitHub stack metadata are unchanged.

Description of Change

Uses span APIs (MemoryExtensions.Split into stackalloc Range[], span numeric parsing) enabled by the prerequisite removing Graphics' netstandard targets.

  • PathBuilder — SVG path-data parsing uses a single-pass span tokenizer instead of chained string replacements, string splits, per-token substrings and a string-token stack. A string replacement still runs when the data contains Infinity. Existing non-SVG recovery quirks (1.5.5, 0011 arc flags, extra m pairs treated as move-tos) are intentionally retained; this is not a general SVG correctness fix.
  • Point/PointF/Size/SizeF/Rect/RectF.TryParse — split into stack ranges and parse spans with the same required part counts, numeric types, NumberStyles and invariant culture. SizeF continues to parse doubles before constructing its result.
  • Insets/InsetsF.Parse — span parsing; still returns zeros on invalid input and ignores entries after the first four, but no longer throws/catches internally. Invalid-input debug output becomes a parsing diagnostic rather than an exception dump.
  • Insets/InsetsF.ToParsableString — formats with string.Create(CultureInfo.InvariantCulture, $"{_top},{_left},{_bottom},{_right}") instead of concatenating four invariant strings; order, comma separators and invariant numeric formatting are unchanged.
  • TextColors — hex parsing uses spans instead of substrings or interpolated strings; result arrays remain allocated.

Graphics.Text.Markdig is a separate project and deliberately excluded from this layer. Its CSS optimization, tests, benchmark and supporting project references belong to a subsequent stack layer.

Benchmarks

Inherited evidence from the supplied combined implementation; not rerun by this session. BenchmarkDotNet, Release, --job short --inProcess (Apple Silicon). The exact benchmark host runtime was not preserved. Allocation numbers are the stronger signal; short-run timings are noisy and do not establish real-world application gains. The complete original command and raw benchmark artifacts were not supplied in the starting body. These measurements predate the rebase onto the net12.0 snapshot; only Graphics operations belonging to this layer are shown below.

Operation Mean before Mean after Allocated before Allocated after
PathBuilder.Build (complex SVG path) 19.45 µs 9.92 µs 48.9 KB 3.07 KB
Point.TryParse 54.05 ns 50.40 ns 112 B 0 B
PointF.TryParse 51.57 ns 45.82 ns 112 B 0 B
Size.TryParse 52.42 ns 53.13 ns 112 B 0 B
SizeF.TryParse 52.17 ns 46.04 ns 112 B 0 B
Rect.TryParse 98.46 ns 88.27 ns 192 B 0 B
RectF.TryParse 100.49 ns 88.48 ns 192 B 0 B
Insets.Parse 92.26 ns 78.25 ns 216 B 48 B
InsetsF.Parse 94.20 ns 79.33 ns 200 B 32 B
TextColors.ParseAsInts 48.99 ns 8.97 ns 136 B 40 B
TextColors parse 28.83 ns 13.83 ns 168 B 40 B

New benchmarks: src/Graphics/tests/Graphics.Benchmarks/ParseBenchmarker.cs (existing PathBenchmarker covers PathBuilder). ToParsableString was not benchmarked.

Behaviour notes

  • Known public behavior change: PathBuilder.ParseFloat(null) now throws Exception instead of NullReferenceException; behavior is not universally identical.
  • Existing, unchanged issue: parsing can loop forever when path data starts with a number or a number follows Z/an unknown command. Not addressed here.
  • Not touched: ColorUtils.cs and NumericExtensions.cs (linked into the netstandard2.0 SourceGen).
  • External libraries/tools that depend on MAUI netstandard2.0/netstandard2.1 reference assemblies still require compatibility evaluation for the prerequisite's target removal. Merging XamlC removal does not establish that compatibility.

Validation

Current rebased head 72c2b3e58cc1c96d785c1d258d1a3cb080ba37ec:

  • dotnet test src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeAndroidTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false --verbosity quiet — passed, including build: 476 succeeded, 0 failed, 0 skipped on net12.0 (arm64).
  • git diff --check 8c97daa2f6953333e3773e2366f67180d368ff2a HEAD — passed; net diff remains 13 Graphics files.
  • Compared full net Graphics patches before and after this prerequisite resync — byte-for-byte identical. Rebase had no conflicts; Markdig source and project-reference changes remain absent. No implementation changes were made during this resync.

Prior validation, not current-head evidence:

  • On the earlier rebased heads 9cad704b6909ba79c91b3e66060b3a6edc14c4c1 and 0b1f29db15f932547bdab8db2cb9d92f6197a8e4, the same full-suite command passed 476/476 on net12.0.
  • On pre-rebase fc9e228df9def1b7dc3995d437a27ef9ac77f200, the same full-suite command passed 473/473 on net11.0; with --filter 'FullyQualifiedName~ParseTests' it passed 30/30. Platform TFMs were disabled in both runs.
  • dotnet format whitespace src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj --no-restore --include src/Graphics/src/Graphics/Insets.cs src/Graphics/src/Graphics/InsetsF.cs src/Graphics/tests/Graphics.Tests/ParseTests.cs --verbosity quiet — passed before rebase; the net patch is unchanged.
  • Earlier unfiltered platform restore attempts were blocked by missing assets (NETSDK1004) or missing iOS workload (NETSDK1147); no tests ran in those attempts. Disabling platform TFMs enabled the successful runs above.

Inherited evidence, not reproduced here: The original combined implementation reportedly passed 472 Graphics.Tests cases (403 existing + 69 new), including CSS cases belonging to the later Markdig layer. New PathBuilderTests/ParseTests reportedly also passed against the old implementation. Old vs new PathBuilder reportedly matched on 300,000 generated paths, including exception type/message in approximately 208,000 throwing cases, using a temporary uncommitted harness. This sampling does not cover the public null exception change or prove all malformed inputs equivalent. Original test/harness commands were not supplied.

No benchmarks, differential harness, or external dependency compatibility validation rerun by this session. CI results have not been evaluated.

Issues Fixed

None — performance and cleanup work, no tracking issue yet.

Let AI finish this PR

  • Let the MAUI agent address review feedback and fix remaining issues on this PR. Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
1 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@kubaflo

kubaflo commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

/review expert-review

@kubaflo

This comment has been minimized.

@github-actions

This comment has been minimized.

@simonrozsival simonrozsival changed the title [net12] Reduce allocations in Graphics parsing Reduce allocations in Graphics parsing Nov 28, 2026
@kubaflo

kubaflo commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

/review expert-review

@kubaflo

This comment has been minimized.

@github-actions

This comment has been minimized.

@simonrozsival
simonrozsival force-pushed the simonrozsival-graphics-parsing-performance branch from fc9e228 to 0b1f29d Compare November 30, 2026 11:35
@github-actions

This comment has been minimized.

@simonrozsival
simonrozsival marked this pull request as ready for review November 30, 2026 11:37
Copilot AI balanced review requested due to automatic review settings November 30, 2026 11:37

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.

🔵 Needs a closer look

The span APIs depend on draft prerequisite #40775 removing Graphics’ netstandard targets, with unresolved external-consumer compatibility and design questions requiring maintainer evaluation before integration.

No open issues 🎉

What changed in this PR

Reduces temporary allocations in .NET MAUI Graphics parsing using span APIs enabled by prerequisite PR #40775. This layer focuses on Graphics; Markdig optimizations remain separate.

Changes:

  • Replaces SVG path string preprocessing and token stacks with a single-pass span tokenizer, retaining existing parsing quirks.
  • Uses span-based geometry, inset, and hex-color parsing, and streamlines invariant inset formatting.
  • Adds parsing regression tests and allocation benchmarks.
File Description
src/​Graphics/​tests/​Graphics.Tests/​PathBuilderTests.cs Adds path-command, malformed-number, and builder-reuse coverage.
src/​Graphics/​tests/​Graphics.Tests/​ParseTests.cs Tests geometry, inset, and color parsing plus invariant formatting.
src/​Graphics/​tests/​Graphics.Benchmarks/​ParseBenchmarker.cs Adds parsing benchmarks with allocation measurements.
src/​Graphics/​src/​Graphics/​Text/​TextColors.cs Parses hex components without temporary strings.
src/​Graphics/​src/​Graphics/​SizeF.cs Uses span splitting while retaining double numeric parsing.
src/​Graphics/​src/​Graphics/​Size.cs Parses size components from spans.
src/​Graphics/​src/​Graphics/​RectF.cs Parses four float components using stack-allocated ranges.
src/​Graphics/​src/​Graphics/​Rect.cs Parses four double components using stack-allocated ranges.
src/​Graphics/​src/​Graphics/​PointF.cs Parses float coordinates without split-string allocations.
src/​Graphics/​src/​Graphics/​Point.cs Parses double coordinates without split-string allocations.
src/​Graphics/​src/​Graphics/​PathBuilder.cs Introduces span tokenization and span-based numeric recovery.
src/​Graphics/​src/​Graphics/​InsetsF.cs Uses span parsing and invariant interpolated formatting.
src/​Graphics/​src/​Graphics/​Insets.cs Uses span parsing and invariant interpolated formatting.

Review effort: Balanced

@kubaflo

kubaflo commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

/review expert-review

@kubaflo

This comment has been minimized.

@simonrozsival
simonrozsival force-pushed the simonrozsival-graphics-parsing-performance branch from 0b1f29d to 9cad704 Compare November 30, 2026 11:58
Copilot AI balanced review requested due to automatic review settings November 30, 2026 11:59
@simonrozsival
simonrozsival force-pushed the simonrozsival-graphics-parsing-performance branch from 9cad704 to 72c2b3e Compare November 30, 2026 12:00

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.

🔵 Needs a closer look

Human compatibility review is needed to confirm whether the documented PathBuilder.ParseFloat(null) exception-type change is acceptable, since static review cannot establish downstream reliance on the existing behavior.

No open issues 🎉

Review effort: Balanced

@github-actions

Copy link
Copy Markdown
Contributor

Selected Tests

@kubaflo — AI-selected UI tests and device tests (GPT-6.2 Sol + MAI Code 2) for commit 0b1f29db.

Result NOT QUEUED Platforms Android, iOS, MacCatalyst, Windows Tests 2 UI, 1 device Commit 0b1f29db


🧪 Test selection — click to expand
Suite Result Selected Build
UI tests ❌ not queued 2 of 77 categories —
Device tests ❌ not queued 1 of 105 units —
🧪 UI tests — GraphicsView, Shape on Android, iOS, MacCatalyst, Windows

❌ Could not queue maui-pr-uitests: The PR was updated while tests were being selected (selected for 0b1f29d, now 72c2b3e). Comment /review run-tests again.

GPT-6.2 Sol: Skip UI tests: the PR changes shared Graphics parsers without changing controls or rendering handlers.
MAI Code 2: Shared Graphics parser allocation changes; runs GraphicsView and Shape UI tests on all platforms, plus the Graphics device suite.

🧪 Running — 2 categories on Android, iOS, MacCatalyst, Windows

Platform Categories
Android GraphicsView, Shape
iOS GraphicsView, Shape
MacCatalyst GraphicsView, Shape
Windows GraphicsView, Shape
🧪 Device tests — Graphics on Android, iOS, MacCatalyst, Windows

❌ Could not queue maui-pr-devicetests: GitHub has no test-merge commit for this PR head (it may have merge conflicts, or GitHub is still computing it). Resolve conflicts or retry /review run-tests.

GPT-6.2 Sol: Run Graphics device tests on Android, iOS, Mac Catalyst, and Windows for the shared parser changes.
MAI Code 2: Shared Graphics parsing changes; runs the Graphics device-test project on all platforms.

🧪 Running — 1 category on Android, iOS, MacCatalyst, Windows

Platform Categories
Android Graphics
iOS Graphics
MacCatalyst Graphics
Windows Graphics
⏭️ Skipped — what neither suite runs

UI tests — 75 categories, 0 platforms

Categories not run: Accessibility, ActionSheet, ActivityIndicator, Animation, AppLinks, Border, BoxView, Brush, Button, CarouselView, CollectionView1, CollectionView2, CollectionView3, CollectionView4, CollectionView5, CollectionView6, CollectionView7, Cells, CheckBox, ContextActions, CustomRenderers, DatePicker, Dispatcher, DisplayAlert, DisplayPrompt, DragAndDrop, Entry, Editor, Effects, Essentials, FlyoutPage, Focus, Fonts, Frame, Gestures, Image, ImageButton, IndicatorView, InputTransparent, IsEnabled, IsVisible, Label, Layout, Lifecycle, ManualReview, Maps, Navigation, Page, Performance, Picker, ProgressBar, RadioButton, RefreshView, SafeAreaEdges, Shadow, ScrollView, SearchBar, Slider, SoftInput, Stepper, Switch, SwipeView, Shell1, Shell2, TabbedPage, TableView, TimePicker, TitleView, ToolbarItem, Triggers, ViewBaseTests, VisualStateManager, Window, WebView, Material3

Each skipped platform and category is listed as a maui-pr-uitests (skipped) … status on this commit. Use /azp run maui-pr-uitests for the full suite.

Device tests — 104 categories, 0 platforms

Categories not run: Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay, Essentials, BlazorWebView

Each skipped platform and project is listed as a maui-pr-devicetests (skipped) … status on this commit. Use /azp run maui-pr-devicetests for the full suite.

🤖 Why these tests — AI rationale (GPT-6.2 Sol + MAI Code 2)

UI tests

Each model chose independently; every test that runs was selected by at least one of them.

Platform GPT-6.2 Sol MAI Code 2
Android — GraphicsView, Shape
iOS — GraphicsView, Shape
MacCatalyst — GraphicsView, Shape
Windows — GraphicsView, Shape

GPT-6.2 Sol — Skip UI tests: the PR changes shared Graphics parsers without changing controls or rendering handlers.

  • PathBuilder changes Graphics path parsing; Controls shape markup uses a separate parser.
  • Geometry, inset, and text-color changes stay in Graphics; no changed UI fixtures or build changes.

MAI Code 2 — Shared Graphics parser allocation changes; runs GraphicsView and Shape UI tests on all platforms, plus the Graphics device suite.

  • Shared src/Graphics parsing changes affect point, size, rectangle, inset, color, and SVG path behavior on every UI platform.
  • PathBuilder changes directly affect shape geometry, selecting Shape; Graphics canvas/path rendering selects GraphicsView.
  • No UI test or host-app infrastructure changed, and the patch does not warrant categories or a full cross-product run beyond these graphics surfaces.

Device tests

Each model chose independently; every test that runs was selected by at least one of them.

Platform GPT-6.2 Sol MAI Code 2
Android Graphics Graphics
iOS Graphics Graphics
MacCatalyst Graphics Graphics
Windows Graphics Graphics

GPT-6.2 Sol — Run Graphics device tests on Android, iOS, Mac Catalyst, and Windows for the shared parser changes.

  • PathBuilder, geometry, insets, and text-color parsing are shared Graphics code.
  • No Controls or Core handlers, other device projects, or test infrastructure changed.

MAI Code 2 — Shared Graphics parsing changes; runs the Graphics device-test project on all platforms.

  • All production changes are under src/Graphics/src/Graphics, mapping to the dedicated Graphics device-test unit.
  • The changes are cross-platform shared code, so android, ios, maccatalyst, and windows are selected.
  • Unit tests and benchmarks changed under src/Graphics/tests; no Controls, Core, Essentials, or shared device-test infrastructure changed, so those suites are omitted.

Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification.

Base automatically changed from simonrozsival-modern-framework-prerequisite to main November 30, 2026 12:43
simonrozsival and others added 3 commits November 30, 2026 13:43
Rewrite the PathBuilder SVG path tokenizer as a single-pass span scanner
(no string replacements, splits, substrings or token stack), and use
MemoryExtensions.Split into stackalloc'd ranges with span-based TryParse in
Point/PointF/Size/SizeF/Rect/RectF.TryParse and Insets/InsetsF.Parse.
TextColors hex parsing and SimpleCssParser also parse from spans.
Behavior is preserved, including PathBuilder's number recovery quirks.

Add PathBuilder and parse tests, and a ParseBenchmarker.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Remove the SimpleCssParser optimization, its tests, benchmark, and project references from the Graphics layer. The original implementation remains available for the subsequent Markdig project PR.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@kubaflo
kubaflo force-pushed the simonrozsival-graphics-parsing-performance branch from 72c2b3e to 1a56e74 Compare November 30, 2026 12:43
@kubaflo
kubaflo merged commit c5b6d9d into main Nov 30, 2026
3 of 4 checks passed
@kubaflo
kubaflo deleted the simonrozsival-graphics-parsing-performance branch November 30, 2026 12:44
kubaflo added a commit that referenced this pull request Nov 30, 2026
<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `538dd1450f5f66508878c4d95ef1be9f25934c25`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8/10 | ↑ One unchanged Markdig patch replayed onto
the final Graphics parent; range-diff reports an identical patch and
exactly five files differ.<br>↑ Fresh net12.0 Graphics.Tests build/run
passed 479/479, including CSS cases.<br>↑ Previous direct review found
no blocking issues; public signatures and normal parsing behavior are
preserved.<br>↓ Benchmark measurements are inherited, not rerun on this
head; real-world gains, mobile execution and current CI results remain
unverified. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

This is next-major (.NET 12) work stacked on #40776
(`simonrozsival-graphics-parsing-performance`). The eventual integration
target is `main`. The Markdig commit was rebased onto final Graphics
parent `72c2b3e58cc1c96d785c1d258d1a3cb080ba37ec`; no inherited Graphics
commits were replayed. GitHub stack metadata is managed separately by
the coordinator.

### Description of Change

<!-- Enter description of the fix in this section -->

Optimizes `Graphics.Text.Markdig` only: `SimpleCssParser.Parse`
enumerates semicolon-separated spans, finds the first colon, and trims
spans before materializing dictionary keys and values. This removes the
split array, declaration strings and pre-trim substrings. Null/empty
input still returns null, declarations without a usable colon are
ignored, and additional colons remain in the value. Duplicate keys still
use the last value, and whitespace-only keys retain their previous
behavior. The old broad per-declaration exception catch is removed
rather than silently swallowing failures.

Adds three CSS test cases and a `ParseCss` benchmark, with Markdig
project references in the existing test and benchmark projects. Other
Graphics-layer content is preserved. The five-file patch originated from
combined source commit `9ad09db697fb90631aba767b18e7c39be4f25277`; the
rebased tree also includes newer parent changes and is not claimed to
match that old tree.

#### Benchmarks

**Inherited measurements, not rerun on this exact head.**
BenchmarkDotNet, Release, `--job short --inProcess`, Apple Silicon;
measured against the combined source branch. The exact runtime version
was not preserved. Allocations are the reliable signal; short-run
timings are noisy and do not establish real-world application gains. The
complete original command and raw artifacts were not supplied.

| Operation | Mean before | Mean after | Allocated before | Allocated
after |
|---|---:|---:|---:|---:|
| **`SimpleCssParser.Parse`** | **107.23 ns** | **75.45 ns** | **896 B**
| **456 B** |

Benchmark: `src/Graphics/tests/Graphics.Benchmarks/ParseBenchmarker.cs`,
method `ParseCss`.

#### Validation

Fresh validation on final rebased head
`538dd1450f5f66508878c4d95ef1be9f25934c25`:

- `LC_ALL=en_US.UTF-8 dotnet test
src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj
-p:IncludeIosTargetFrameworks=false
-p:IncludeMacCatalystTargetFrameworks=false
-p:IncludeAndroidTargetFrameworks=false
-p:IncludeMacOSTargetFrameworks=false --verbosity quiet` — **passed**,
project built and 479/479 full Graphics.Tests passed, including CSS
cases; 0 failed, 0 skipped, `net12.0|arm64`. Mobile/platform TFMs
disabled.
- `git range-diff
0b1f29d..c63116a
72c2b3e..HEAD` — **passed**, one
Markdig commit before and after, identical patch (`=`).
- `git diff --check` — **passed**; final diff against parent contains
exactly the five requested files and no changes outside them. Rebase was
pushed with an explicit force-with-lease against the previous remote
head `c63116a21367f2636942ecfafaddf93939dd4600`.

Historical validation on previous head
`c63116a21367f2636942ecfafaddf93939dd4600` (not represented as new runs
on the final head):

- `LC_ALL=en_US.UTF-8 dotnet test
src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj
-p:IncludeIosTargetFrameworks=false
-p:IncludeMacCatalystTargetFrameworks=false
-p:IncludeAndroidTargetFrameworks=false
-p:IncludeMacOSTargetFrameworks=false --filter
'FullyQualifiedName~ParseTests' --verbosity quiet` — **passed**, 33/33
parse tests, including all three CSS cases; `net12.0|arm64`.
- The full Graphics.Tests command above also passed 479/479 on that
head, with and without `--no-build --no-restore`.
- `LC_ALL=en_US.UTF-8 dotnet build
src/Graphics/tests/Graphics.Benchmarks/Graphics.Benchmarks.csproj -c
Release -p:IncludeIosTargetFrameworks=false
-p:IncludeMacCatalystTargetFrameworks=false
-p:IncludeAndroidTargetFrameworks=false
-p:IncludeMacOSTargetFrameworks=false --verbosity quiet` — **passed**, 0
warnings, 0 errors. Build only; benchmarks were not executed.

Historical validation on original pre-rebase head
`b8c328263812a135cd1e5b534c33ea59e0a56d39`: the same test commands
passed 29/29 parse tests and 472/472 full Graphics.Tests on `net11.0`;
the Release benchmark build passed. `dotnet format whitespace
src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj --no-restore
--include src/Graphics/src/Text.Markdig/Renderer/SimpleCssParser.cs
src/Graphics/tests/Graphics.Tests/ParseTests.cs
src/Graphics/tests/Graphics.Benchmarks/ParseBenchmarker.cs --verbosity
quiet` passed then. `git diff --exit-code 9ad09db -- src/Graphics`
was empty then; neither historical check is represented as a fresh check
on the rebased tree.

Previous direct finalization review found no blocking issues in the
parser, test/benchmark references or layer scope; the patch remains
unchanged. No benchmark timing/allocation measurements, differential
harness or mobile-platform tests were rerun here. Current CI results
have not been inspected. On previous head
`c63116a21367f2636942ecfafaddf93939dd4600`, lightweight GitHub checks
passed and Build Insights was pending; no `maui-pr` Azure DevOps build
was reported for the stacked base. Those results do not validate this
final head.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

None — performance optimization; no tracking issue supplied.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 30, 2026
<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `cf57bdcbc1252842694ac16b2fde1fe5016c2811`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8/10 | ↑ 1,407 Core tests and 67 focused Controls
tests pass on this head; .NET 11 iOS and overridden Android builds
compile.<br>↑ Parent/head benchmarks demonstrate allocation reductions
on the identical pre-rebase patch.<br>↓ Intended .NET 12 mobile builds
and device behavior remain unverified; external package compatibility
and application-level performance need evaluation. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

This is coordinated .NET 12 stacked work, based on #40778 (Markdig),
above #40776 (Graphics) and #40775 (framework prerequisite). #40608
(XamlC removal) is now merged.

### Description of Change

<!-- Enter description of the fix in this section -->

Reduce allocations in Core event dispatch, converters, font handling and
Flex ordering. This layer derives from
`add9b583732112c414b3ba410fd10d8ff92396a4`, with adjustments for
upstream easing and layout changes.

- Use a pooled WeakEventManager dispatch snapshot and in-place
dead-subscriber cleanup. **MethodInfo.Invoke is retained**, so handler
exceptions remain wrapped in `TargetInvocationException`. Tests cover
subscribe/unsubscribe during raises, dead-subscriber cleanup and
throwing handlers.
- Reduce temporary strings in CornerRadius, Thickness, SafeAreaEdges,
Easing and Keyboard converters and font handling. Easing keeps the
upstream parser for function/CSS syntax and adds a fast path for named
curves.
- Reduce ordered-child Flex allocations while preserving stable
ordering. Upstream Flex wrap-line and Grid changes are retained; this
layer does not independently implement the earlier Grid optimization.
- Add converter, event, font and Flex ordering tests and three benchmark
fixtures.

**Compatibility risk:** prerequisite #40775 removes MAUI netstandard
reference targets. On this head, a `netstandard2.0` or `netstandard2.1`
project directly referencing Core fails restore with NU1201; the same
probe targeting `net12.0` restores. This demonstrates a direct-reference
break, not a failure of all netstandard dependencies. NuGet package
consumers, external dependencies and migration paths need broader
discussion and validation before merge.

#### Benchmark data

BenchmarkDotNet Release, `--job short --inProcess`, Apple M5 Max, .NET
12.0.0 (12.0.26.55201). These measurements compare the **previous**
parent `c63116a21367f2636942ecfafaddf93939dd4600` with head
`36c0aad8bcd8f27fff4e27c328c4192d758b790c`, not the current rebased
head. The layer patch and benchmarked source files are unchanged by the
latest rebase. Each run had three warmups and three measurements;
process-priority elevation was denied. Timings are noisy; allocations
are the more reliable signal.

| Operation | Mean parent | Mean head | Allocated parent | Allocated
head |
|---|---:|---:|---:|---:|
| **WeakEventManager raise, no handlers** | **6.00 ns** | **0.334 ns** |
**64 B** | **0 B** |
| **WeakEventManager raise, 1 handler** | **38.47 ns** | **30.07 ns** |
**192 B** | **40 B** |
| **WeakEventManager raise, 5 handlers** | **148.91 ns** | **98.77 ns**
| **504 B** | **40 B** |
| `Thickness` from XAML string | 81.19 ns | 75.33 ns | 232 B | 48 B |
| `Thickness` from CSS string | 73.32 ns | 65.09 ns | 192 B | 48 B |
| `Thickness` to string | 140.01 ns | 111.38 ns | 200 B | 96 B |
| `CornerRadius` from XAML string | 81.03 ns | 64.16 ns | 208 B | 56 B |
| `CornerRadius` to string | 124.17 ns | 108.15 ns | 200 B | 104 B |
| `SafeAreaEdges` from string | 73.09 ns | 35.23 ns | 384 B | 32 B |
| `Easing` from string | 21.69 ns | 4.26 ns | 48 B | 0 B |
| **`Keyboard` from string** | **84.93 ns** | **4.13 ns** | **256 B** |
**0 B** |
| Flex with ordered children | 1,046.5 ns | 742.9 ns | 1,056 B | 184 B |
| Flex wrap with AlignContent | 643.8 ns | 634.6 ns | 264 B | 240 B |
| Grid with collapsed children | 543.6 ns | 516.0 ns | 1,384 B | 1,384 B
|

The Flex-wrap and Grid rows are context, not claims of separate
wrap-line or Grid optimizations in this layer.

<details>
<summary>Historical measurements from the original combined source
branch</summary>

BenchmarkDotNet Release, `--job short --inProcess`, Apple Silicon; exact
runtime version was not preserved. These pre-rebase results are not
measurements of the current PR delta. In particular, upstream has since
incorporated the earlier Flex-wrap and Grid work.

| Operation | Mean before | Mean after | Allocated before | Allocated
after |
|---|---:|---:|---:|---:|
| **WeakEventManager raise, no handlers** | **5.5 ns** | **0.4 ns** |
**64 B** | **0 B** |
| **WeakEventManager raise, 1 handler** | **36.8 ns** | **33.2 ns** |
**192 B** | **40 B** |
| **WeakEventManager raise, 5 handlers** | **138.6 ns** | **122.6 ns** |
**504 B** | **40 B** |
| `Thickness` from XAML string | 109 ns | 80 ns | 232 B | 48 B |
| `Thickness` from CSS string | 90 ns | 71 ns | 192 B | 48 B |
| `Thickness` to string | 132 ns | 107 ns | 200 B | 96 B |
| `CornerRadius` from XAML string | 94 ns | 77 ns | 208 B | 56 B |
| `CornerRadius` to string | 124 ns | 113 ns | 200 B | 104 B |
| `SafeAreaEdges` from string | 61 ns | 34 ns | 384 B | 32 B |
| `Easing` from string | 23 ns | 4.7 ns | 128 B | 0 B |
| **`Keyboard` from string** | **82 ns** | **4.3 ns** | **256 B** | **0
B** |
| Flex wrap with AlignContent | 617 ns | 592 ns | 664 B | 192 B |
| Flex with ordered children | 941 ns | 744 ns | 1056 B | 184 B |
| Grid with collapsed children | 647 ns | 640 ns | 2376 B | 2192 B |

</details>

#### Validation performed

SDK `12.0.100-alpha.1.26551.101`; final head
`cf57bdcbc1252842694ac16b2fde1fe5016c2811`:

```sh
dotnet build src/Core/tests/UnitTests/Core.UnitTests.csproj -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:q
# PASS: 0 warnings, 0 errors.
LC_ALL=en_US.UTF-8 dotnet artifacts/bin/Core.UnitTests/Debug/net12.0/Microsoft.Maui.UnitTests.dll --no-ansi --progress off --output Minimal
# PASS: 1,407 passed, 0 failed.

dotnet build src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:q
# PASS: 0 warnings, 0 errors.
LC_ALL=en_US.UTF-8 dotnet artifacts/bin/Controls.Core.UnitTests/Debug/net12.0/Microsoft.Maui.Controls.Core.UnitTests.dll --filter-class 'Microsoft.Maui.Controls.Core.UnitTests.FontUnitTests' --filter-class '*EasingFactoryTests' --no-ansi --progress off --output Minimal
# PASS: 67 passed, 0 failed.

dotnet build src/Core/src/Core.csproj -f net11.0-ios27.0 -p:IncludePreviousTfms=true -p:IncludePreviousTfmsEssentials=true -p:IncludePreviousTfmsGraphics=true -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=true -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:q
# PASS: 0 warnings, 0 errors.

dotnet build src/Core/src/Core.csproj -f net11.0-android37.0 -p:TargetFrameworks=net11.0-android37.0 -p:IncludePreviousTfms=true -p:IncludePreviousTfmsEssentials=true -p:IncludePreviousTfmsGraphics=true -p:IncludeAndroidTargetFrameworks=true -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false -v:q
# PASS: 1 Gradle warning about an SDK XML version; 0 errors. Uses an explicit platform-target override.
```

The installed workloads are .NET 11-era. The intended .NET 12 Android
and iOS targets were not compiled locally: previous attempts failed with
NETSDK1139 and NETSDK1140 respectively. The .NET 11 Android build above
uses an overridden Android 37 target, not the repository's normal
previous-framework Android target. No mobile device tests or
application-level performance validation were run; current CI results
have not been inspected.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

N/A: performance-focused stack; no issue-closing reference.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 30, 2026
<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `26c9bd3ae7e055ad1fc75b512b9974cb21ad72df`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8/10 | ↑ Conflict-free rebase onto Core parent
cf57bdc; all six commits are
patch-identical by range-diff.<br>↑ BuildTasks Debug and Controls net12
Release builds succeeded with 0 warnings/errors; 376 focused tests
passed on this head.<br>↑ Previous-head full suite failure identities
matched its prior parent: Release 19 and Debug 31.<br>↓ Full suite and
parent-baseline comparison were not rerun for this latest rebase.<br>↓
Historical incremental row/column allocations increased from 12.5 KB to
14.84 KB per 100 conversions; benchmarks were not rerun after
rebase.<br>↓ Platform validation and post-rebase CI results remain
unverified. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

This is next-major .NET 12 work stacked directly on #40779
(`simonrozsival-net12-core-allocations`), not a servicing fix. Earlier
layers are #40778 (Markdig), #40776 (Graphics), and #40775. After #40608
merged into main and the lower stack was synchronized with newer main,
this layer was rebased onto parent
`cf57bdcbc1252842694ac16b2fde1fe5016c2811`; its tests target `net12.0`.
The PR base, stack metadata and ready-for-review state are unchanged.

### Description of Change

<!-- Enter description of the fix in this section -->

Reduce transient parsing allocations in Controls.Core: binding paths,
bindable property names, FontAttributes, point/path collections,
VisualElement transforms, Shell URI query separation and route parameter
extraction. Brush parsing reuses separator arrays and uses spans for
selected tokens/numbers, but **BrushTypeConverter still splits strings;
this is not a full span-based parser rewrite**.

Follow-up cleanup replaces rented string arrays in row/column formatting
and LINQ/string.Join in point formatting with indexed StringBuilder
loops. Row/column loops share an internal Core
`GridLengthTypeConverter.AppendTo` helper using invariant interpolated
numeric appends, a separate `*`, and literal `auto`, without per-item
strings. Empty and single-grid-item fast paths remain unchanged.
FontAttributes returns constant outcomes for the Bold/Italic mask while
ignoring unknown bits. Path figures use invariant interpolated
coordinate appends, preserving separators/trailing spaces and the
existing current-culture formatting of arc sizes/rotation. **This
simpler StringBuilder approach increased measured row/column
allocations; it is not an allocation improvement for those operations.**

Adds focused behavior-preservation tests for binding paths, font
attributes, transforms, route parameter names, URI/query handling, and
formatter culture/extreme/empty/large-count output. Three benchmark
files live in Core.Benchmarks but exercise Controls.Core.

The initial layer contained the 19 non-Xaml files from source commit
`5d24a694eb3d8de21ead5965d743995ae3a1b1d0`. Follow-up
formatter/helper/test changes mean final files no longer exactly match
that source. **XamlComponentRegistry optimization is explicitly
excluded** from this layer. SourceGen-linked parser files are untouched.

#### Benchmark measurements (inherited combined-source run)

These measurements were supplied from the earlier combined-source
before/after run, **not rerun on this isolated PR and not measurements
of the final formatting cleanup or rebased net12 head**.
BenchmarkDotNet, Release, `--job short --inProcess`, Apple Silicon. The
exact runtime was not preserved; these are **not claimed to be .NET 12
runtime measurements**. Timing means are noisy and error/interval data
is unavailable, so small mean differences cannot establish a speedup or
regression. These historical allocation reductions do not establish the
final layer's allocation profile.

| Operation | Mean before | Mean after | Allocated before | Allocated
after |
|---|---:|---:|---:|---:|
| Binding simple | 728 ns | 584 ns | 544 B | 512 B |
| Binding nested | 1277 ns | 1146 ns | 1016 B | 968 B |
| Binding indexer | 1843 ns | 1877 ns | 1568 B | 1432 B |
| VisualElement transform | 342 ns | 290 ns | 688 B | 120 B |
| PointCollection | 302 ns | 265 ns | 1304 B | 848 B |
| FontAttributes | 45 ns | 28 ns | 176 B | 24 B |
| LinearGradientBrush | 5846 ns | 5469 ns | 9344 B | 8968 B |
| RadialGradientBrush | 4412 ns | 4252 ns | 6888 B | 6600 B |
| PathFigureCollection | 2273 ns | 2176 ns | 3624 B | 3368 B |
| BindableProperty | 399 ns | 426 ns | 400 B | 360 B |
| Shell ConvertToStandardFormat | 196 ns | 192 ns | 1112 B | 1016 B |
| Shell leading `..` | 70 ns | 53 ns | 344 B | 272 B |
| Route GetSegmentParameterName | 11.5 ns | 7.7 ns | 72 B | 32 B |
| Route mixed parameter | 23.8 ns | 14.0 ns | 72 B | 32 B |
| Route template parse | 151 ns | 157 ns | 920 B | 888 B |

#### Incremental GridDefinitionBenchmarker comparison

Coordinator-supplied measurements compare before
`e91ce337a0d7a689a8ed08b3692c7205223528d2` with after
`d08fb8f4808bf01b7460df07ce6839740a9cca9a` (both before the rebase).
**Each operation performs 100 conversions**; times and allocations below
are per 100 conversions, not per conversion. BenchmarkDotNet in-process,
Apple M5 Max, .NET 11. The separate before benchmark build failed, so
the before run used the after benchmark build with Core and Controls
DLLs swapped to the earlier head. This is an incremental cleanup
comparison, not an independently rebuilt comparison of the entire stack.
It was already run centrally, not rerun by this worker or after the
rebase.

| Operation (100 conversions) | Mean before | Mean after | Allocated
before | Allocated after |
|---|---:|---:|---:|---:|
| ColumnConvertTo | 6.771 us | 6.621 us | 12.5 KB | 14.84 KB |
| RowConvertTo | 6.828 us | 6.235 us | 12.5 KB | 14.84 KB |

**Allocated memory increased in both operations.** No clear speedup is
inferred from these noisy timing means; error/interval data is
unavailable here.

#### Validation after latest stack sync

Commands executed from repository root at
`26c9bd3ae7e055ad1fc75b512b9974cb21ad72df`, on parent
`cf57bdcbc1252842694ac16b2fde1fe5016c2811`. Platform TFMs were disabled
only through command-line properties.

```sh
LC_ALL=en_US.UTF-8 dotnet build Microsoft.Maui.BuildTasks.slnf -c Debug -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false --nologo -v:q
LC_ALL=en_US.UTF-8 dotnet build src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Release -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false --nologo -v:q
```
Result: **both passed**, each with 0 warnings and 0 errors.

```sh
LC_ALL=en_US.UTF-8 dotnet artifacts/bin/Controls.Core.UnitTests/Release/net12.0/Microsoft.Maui.Controls.Core.UnitTests.dll --parallel none --filter-class '*ColumnDefinitionCollectionTypeConverterUnitTests' '*GridLengthTypeConverterTests' '*FontAttributeConverterUnitTests' '*PathFigureCollectionConverterTests' '*PointCollectionTests' '*BindingExpressionTests' '*ShellRouteTemplatesTests' '*ShellUriHandlerTests' '*VisualElementTests'
```
Result: **passed**, 376 tests, 0 failed, 0 skipped.

`git diff --check cf57bdc..HEAD`
passed. `git range-diff
36c0aad..779ee7c
cf57bdc..HEAD` reported all six commits
patch-identical. Rebase was conflict-free. Full-suite Debug/Release runs
and a baseline comparison against the latest parent were **not rerun**;
the previous evidence below is historical, not a full-suite result on
this head.

#### Historical validation after previous rebase

Commands executed from repository root at
`779ee7c046ccd3a68bc90f48d9ce96b3f04dcf9d`. Platform TFMs were disabled
only through command-line properties. Upstream migrated the test project
to xUnit v3/Microsoft.Testing.Platform, so the test executable is run
directly instead of the historical xunit.console v2 runner.

```sh
LC_ALL=en_US.UTF-8 dotnet build Microsoft.Maui.BuildTasks.slnf -c Debug -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false --nologo -v:q
LC_ALL=en_US.UTF-8 dotnet build src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Debug -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false --nologo -v:q
LC_ALL=en_US.UTF-8 dotnet build src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Release -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false --nologo -v:q
```
Result: **all passed**, each with 0 warnings and 0 errors. Release was
rebuilt again after the parent-baseline comparison.

```sh
LC_ALL=en_US.UTF-8 dotnet artifacts/bin/Controls.Core.UnitTests/Release/net12.0/Microsoft.Maui.Controls.Core.UnitTests.dll --parallel none
```
Result: **19 failures**, 7,815 passed, 30 skipped (7,864 total). A fresh
Release build/run of the same command on parent
`36c0aad8bcd8f27fff4e27c328c4192d758b790c` reproduced the **same exact
19 failure identities**: 18 `CommandsSubscribedToCanExecuteCollect`
GC-lifetime cases and `CurrentPageNotNullPoppingRoot(useMaui: True)`.
Parent result: 7,716 passed, 19 failed, 30 skipped (7,765 total). These
failures were not attributed to this layer; they remain unresolved
historical baseline limitations and have not been rechecked against the
latest parent.

```sh
LC_ALL=en_US.UTF-8 ./artifacts/bin/Controls.Core.UnitTests/Debug/net12.0/Microsoft.Maui.Controls.Core.UnitTests
```
Result: **31 failures**, 7,803 passed, 30 skipped (7,864 total). The
same command on a fresh Debug build of parent
`36c0aad8bcd8f27fff4e27c328c4192d758b790c`, run back-to-back, gave 31
failures, 7,704 passed, 30 skipped (7,765 total), with **identical
failure identities**: the Release 19 plus GC-lifetime leak assertions
(`DoesNotLeak`, `LayoutDoesNotLeakAfterChildRemoved`,
`RowDefinitionDoesNotLeak`, `TransformGroupTests` subscription leaks and
similar) that depend on Debug JIT object lifetimes. They were not
attributed to this layer. The historical xunit.console v2 invocation
failed to load `xunit.abstractions` after the upstream runner migration
and was replaced with the direct v3 executable.

```sh
LC_ALL=en_US.UTF-8 dotnet artifacts/bin/Controls.Core.UnitTests/Release/net12.0/Microsoft.Maui.Controls.Core.UnitTests.dll --parallel none --filter-class '*ColumnDefinitionCollectionTypeConverterUnitTests' '*GridLengthTypeConverterTests' '*FontAttributeConverterUnitTests' '*PathFigureCollectionConverterTests' '*PointCollectionTests' '*BindingExpressionTests' '*ShellRouteTemplatesTests' '*ShellUriHandlerTests' '*VisualElementTests'
```
Result: **passed**, 376 tests, 0 failed, 0 skipped.

`git diff --check 36c0aad..HEAD` passed on that previous head.
Historical pre-rebase evidence: initial split full-suite run passed
6,931 tests with 30 skipped; pre-rebase final formatter run passed 76
tests, and the initial Release benchmark build passed. These are
historical results, not latest net12 rebase validation. The older CSS
ordering flake was not observed in the serial Release previous-rebase
run.

Platform/device/UI validation and post-rebase CI investigation have not
been performed; no CI success is claimed. Benchmark measurements were
not rerun after rebasing.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

No bug issue is closed; this is a performance and formatting cleanup
layer. Relates to #40779 and the merged #40608.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 30, 2026
<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `f1dfc0cea27b57c5f26e4d62c16df76d650ca3c0`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8.5/10 | ↑ Single-file change; set membership is
unchanged because entries are only created by
Register/RegisterTemplateComponent and removed by Unregister/GC.<br>↑
Run locally on this head: Controls.Xaml.UnitTests 1652 passed / 3
skipped / 0 failed; SourceGen.UnitTests 999 total / 71 skipped / 0
failed; 41 focused registry/hot-reload Controls.Core tests passed.<br>↓
GetInstances is now O(all registered pages) instead of O(pages of that
type), and enumeration order is not formally guaranteed.<br>↓ No
benchmark recorded; full Controls.Core.UnitTests, platform TFM builds,
device tests and CI not run on this head.<br>↓ Inherited, not rerun
here: parent #40780 has 19 full-suite Controls.Core.UnitTests failures
that reproduce identically on its Core parent #40779. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

<!-- Enter description of the fix in this section -->

**Stack** (bottom → top, on `main` after #40608 merged): #40775 (drop
netstandard prerequisite) → #40776 (Graphics) → #40778 (Markdig) →
#40779 (Core) → #40780 (Controls.Core) → **this PR (Controls.Xaml)**.
Base branch is `simonrozsival-net12-controls-parsing-allocations`
(#40780); review only the diff against it.

Now that Controls.Xaml no longer targets `netstandard2.0`,
`ConditionalWeakTable<TKey,TValue>` is enumerable. The secondary
per-type index that existed only to work around that limitation is
removed:

- Removed `s_instancesByType` (`Dictionary<Type,
List<WeakReference<object>>>`) and its lock.
- Removed `TrackInstance` / `UntrackInstance` and the
`ComponentMap.IsNew` first-registration bookkeeping from `Register` /
`RegisterTemplateComponent` / `Unregister`.
- `GetInstances(Type)` now enumerates `s_table` directly and returns
pages whose `GetType() == pageType`.

Single file: `src/Controls/src/Xaml/XamlComponentRegistry.cs` (+5 /
−78).

**Benchmarks:** none recorded for this change. It is a simplification
that removes a global lock, a `WeakReference<object>` allocation and a
dead-entry pruning pass from the first registration of each page; no
performance numbers are claimed.

**Semantic notes / risks:**

- **Membership:** unchanged. `s_table` entries are only created by
`Register`/`RegisterTemplateComponent` (same triggers that previously
called `TrackInstance`) and removed by `Unregister` or GC.
- **Type matching:** still exact-type (`GetType() == pageType`),
matching the old `page.GetType()` dictionary key; derived types are not
returned.
- **Ordering:** previously insertion order per type.
`ConditionalWeakTable` enumeration is in practice insertion order but
not formally documented; callers (hot reload) should not depend on
order.
- **Cost:** `GetInstances` now scans all registered pages rather than
only those of the requested type. It is a hot-reload-only path and the
set of live pages is small, but this trades a per-registration cost for
a per-lookup scan.
- **Thread safety:** `ConditionalWeakTable` enumeration is safe
concurrently with adds/removes; entries added or removed during
enumeration may or may not be observed, which is equivalent to the old
snapshot-under-lock semantics.

**Validation** (run locally on head `f1dfc0cea2`, macOS, net12, platform
TFMs disabled via `-p:IncludeAndroidTargetFrameworks=false
-p:IncludeIosTargetFrameworks=false
-p:IncludeMacCatalystTargetFrameworks=false
-p:IncludeWindowsTargetFrameworks=false
-p:IncludeMacOSTargetFrameworks=false`):

- `dotnet build Microsoft.Maui.BuildTasks.slnf …`, then
`Controls.Xaml.UnitTests.csproj`, `SourceGen.UnitTests.csproj`,
`Controls.Core.UnitTests.csproj` — passed, 0 errors.
- `LC_ALL=en_US.UTF-8 dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj
--no-build` — **passed**: 1652 passed, 3 skipped, 0 failed.
- `dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj
--no-build` (includes hot-reload tests) — **passed**: 999 total, 71
skipped, 0 failed.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--no-build --filter
"FullyQualifiedName~XamlComponentRegistry|FullyQualifiedName~XamlIncrementalHotReload|FullyQualifiedName~HotReload"`
— **passed**: 41 passed, 0 failed.
- **Not run on this head:** full Controls.Core.UnitTests, platform TFM
builds, device tests, CI.
- **Known inherited limitation (from the parent layer, not rerun
here):** on parent #40780 the full Controls.Core.UnitTests suite has 19
failures, and the same 19 reproduce identically on its Core parent
#40779. This PR does not touch Controls.Core, so they are not expected
to change here, but that has not been verified on this head.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Fixes # N/A — part of the net12 netstandard-removal stack.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 30, 2026
<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `6f75ab472d03f5dc70154418240bf2338f098b65`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8/10 | ↑ Both Essentials commits rebased without
changes, confirmed by range-diff; review found no substantive issue in
traversal checks, coordinate conversion or query decoding.<br>↑ All 550
Essentials tests pass on net12.0; unit-test and Release benchmark builds
succeed without warnings.<br>↓ Platform builds and external-consumer
compatibility remain unverified; inherited benchmark measurements do not
cover the formatting follow-up; CI validation is not complete. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

.NET 12 stack: this layer targets
`simonrozsival-net12-simplify-xaml-component-registry` (#40782), rather
than duplicating its prerequisite changes against `main`.

### Description of Change

<!-- Enter description of the fix in this section -->

**Prepared for review following the XamlC removal. Broader discussion
and evaluation of external consumers requiring netstandard remain
necessary before merging the stack. Essentials is also consumed
standalone, so compatibility must be evaluated beyond applications using
the full MAUI stack.**

Current prerequisite stack, bottom to top: #40775 (drop netstandard) →
#40776 (Graphics) → #40778 (Markdig) → #40779 (Core) → #40780
(Controls.Core) → #40782 (Controls.Xaml) → this PR. The former
XamlC-removal prerequisite #40608 is now incorporated upstream. This
layer's two commits are rebased onto parent
`f1dfc0cea27b57c5f26e4d62c16df76d650ca3c0` without patch changes.

Use spans for relative-path segment validation, latitude/longitude
parsing, and query parameter decoding. Query values containing `+` use a
reusable stack buffer up to 256 characters, with a heap buffer for
larger values. Format `LocationTypeConverter.ConvertTo` output with
`string.Create(CultureInfo.InvariantCulture, ...)`, avoiding two
intermediate numeric strings while preserving the exact output and
`NotSupportedException` behavior. Add 30 test cases covering traversal
segments, malformed coordinates, exact location formatting, invariant
culture, invalid conversion values, query decoding and stack-buffer
boundaries. TextToSpeech chunking is intentionally skipped: chunks are
strings anyway.

This layer contains Essentials only, plus its benchmark methods. The six
Essentials files are taken from
`04fb9f8a715163e48978e576bdf31c8c33d1b488`, plus a follow-up limited to
`LocationTypeConverter.ConvertTo` and its tests. The benchmark differs
from that source only by omitting the Maps import, field and method.
Maps code, Maps tests and `Core.Benchmarks.csproj` are unchanged; Maps
follows in a separate layer.

**Inherited benchmark measurements — not re-run in this layer, and they
do not measure the `ConvertTo` formatting follow-up.** BenchmarkDotNet
Release, `--job short --inProcess`, Apple Silicon; measured on the
combined Essentials/Maps source. The exact runtime was not preserved, so
no runtime version is claimed. Allocations are reliable; timings are
noisy short-run measurements, not guaranteed real-world gains.

| Operation | Mean before | Mean after | Allocated before | Allocated
after |
|---|---:|---:|---:|---:|
| **`FileSystemUtils.IsValidRelativePath`** | **45.6 ns** | **9.2 ns** |
**288 B** | **0 B** |
| **`WebUtils.ParseQueryString`** | **229.2 ns** | **183.9 ns** | **1192
B** | **880 B** |
| `LocationTypeConverter.ConvertFrom` | 135.2 ns | 99.5 ns | 440 B | 208
B |

**Validation re-run at the assessed rebased head:**

```bash
dotnet build src/Essentials/test/UnitTests/Essentials.UnitTests.csproj -p:IncludeAndroidTargetFrameworks=false -p:IncludeiOSTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false --verbosity quiet
```
Passed: 0 warnings, 0 errors.

```bash
LC_ALL=en_US.UTF-8 dotnet test --project src/Essentials/test/UnitTests/Essentials.UnitTests.csproj --no-build -p:IncludeAndroidTargetFrameworks=false -p:IncludeiOSTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false
```
Passed on net12.0/arm64: 550 tests, 0 failed, 0 skipped, including the
30 new cases. Local SDK: `12.0.100-alpha.1.26551.101`. The old
xunit.console v2 invocation failed to load `xunit.abstractions`; the
parent migrated this test project to xUnit
v3/Microsoft.Testing.Platform, so validation now uses its supported
`dotnet test` runner. No test failure or source fix was needed.

```bash
dotnet build src/Core/tests/Benchmarks/Core.Benchmarks.csproj -c Release -p:IncludeAndroidTargetFrameworks=false -p:IncludeiOSTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false --verbosity quiet
git range-diff 2bfe1fa..27de68a f1dfc0c..HEAD
git diff --check
```
Passed: Release benchmark build has 0 warnings, 0 errors and no Maps
reference; range-diff confirms both commits are unchanged; whitespace
check is clean.

**Previously run before rebase, not re-run:**

```bash
dotnet format Microsoft.Maui.sln --no-restore --include src/Essentials/src/FileSystem/FileSystemUtils.shared.cs src/Essentials/src/Types/LocationTypeConverter.shared.cs src/Essentials/src/Types/Shared/WebUtils.shared.cs src/Essentials/test/UnitTests/FileSystemUtils_Tests.cs src/Essentials/test/UnitTests/LocationTypeConverter_Tests.cs src/Essentials/test/UnitTests/WebUtils_Tests.cs src/Core/tests/Benchmarks/Benchmarks/EssentialsMapsBenchmarker.cs --exclude Templates/src --exclude-diagnostics CA1822 --verbosity quiet
git diff --stat 04fb9f8 HEAD -- src/Essentials
```
Passed before rebase: formatting completed; the Essentials source
comparison contained only the `LocationTypeConverter` follow-up and its
tests. The rebase preserved both patches unchanged. Platform builds,
external-consumer compatibility and benchmark execution were not run in
this layer. CI is not claimed green: Build Insights is in progress; the
required `ci-analysis` skill was unavailable for detailed AzDO
verification. Ready for human review does not imply ready to merge.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

N/A — performance modernization; no bug issue is claimed fixed.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants