Repository navigation
perf(SKSurface): cache the Canvas wrapper across calls - #4247
Merged
Merged
Conversation
SKSurface.Canvas did a P/Invoke (sk_surface_get_canvas) plus a locked HandleDictionary lookup and an OwnedBy registration on every access. In draw-heavy render loops that fetch the canvas per draw call, that overhead becomes a measurable bottleneck. Skia's SkSurface lazily creates its SkCanvas once and returns the same raw pointer for the surface's entire lifetime (SkSurface_Base::getCachedCanvas, shared by all backends), so the managed wrapper is stable too. Cache it on first access and reuse it, re-fetching only if the cached wrapper was disposed out from under us. The cache is dropped on surface disposal. Per-getter cost drops from ~31 ns to ~0.67 ns (a field read + handle check), zero allocations; fetching Canvas per draw now matches hand-caching it. Adds SKSurfaceTest coverage (same-instance return, re-fetch after explicit canvas dispose) and a SurfaceCanvasBenchmark simulating a 1,000-draw/frame render loop. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Contributor
📦 Try the packages from this PRWarning Do not run these scripts without first reviewing the code in this PR. Step 1 — Download the packages bash / macOS / Linux: curl -fsSL https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.sh | bash -s -- 4247PowerShell / Windows: iex "& { $(irm https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.ps1) } 4247"Step 2 — Add the local NuGet source dotnet nuget add source ~/.skiasharp/hives/pr-4247/packages --name skiasharp-pr-4247More options
Or download manually from Azure Pipelines — look for the Remove the source when you're done: dotnet nuget remove source skiasharp-pr-4247 |
Contributor
|
Hey there @@ramezgerges! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
Contributor
|
/azp run |
|
No pipelines are associated with this pull request. |
mattleibow
added a commit
that referenced
this pull request
Jul 8, 2026
…ready (#4361) [skills] Add performance-fixer skill + make the benchmark harness AI-ready (#4361) Context: dotnet/aspnetcore optimize-aspnetcore-performance (reference architecture) Related: #4241 (SKMatrix native→managed, up to 24×), #4345 (SKColor alloc-free parse), #4247 (SKSurface.Canvas caching), #4362 (perf/* label taxonomy), #4330 (memory-leak-fixer) SkiaSharp is a thin managed wrapper over native Skia, so its recurring, high-impact performance family is the tax the C# layer adds between the caller and Skia — a P/Invoke transition paid for math that is a few float ops, an allocation on a hot parse/convert path, a native lookup redone on every getter, or per-element marshalling in a loop. We have merged several such wins by hand (#4241, #4345, #4247); this adds an autonomous scanner so more of them surface as code lands, without a human hunting for them. Add a `performance-fixer` skill (sibling to `memory-leak-fixer`) plus a scheduled gh-aw workflow that scans the managed binding for one hot-path opportunity, proves it, fixes it (managed-only, ABI-safe), and files a linked issue + draft PR. The defining discipline is two proofs, which a generic perf pass lacks: every fix must be shown FASTER (a BenchmarkDotNet New-vs-Old measurement) AND behaviour-IDENTICAL (an equivalence test — bit-exact vs SkiaApi.sk_* for numeric ports, across edge inputs, and mutation-checked to prove it catches divergence). A faster answer that differs from Skia is a rendering regression, not a win, so it is rejected. The skill also encodes the traps we learned the hard way: the x86/x87 float-determinism native fallback (#4241), the ARM64 Vector256 regression, statistical benchmark rigor, and full behaviour parity including exceptions, ownership/GC.KeepAlive lifetime, and rendered pixels. ~~ Reference structure ~~ References are split by area (mirroring the aspnetcore skill): references/hot-paths/* (SkiaSharp code areas — geometry-math, color, handles-and-collections, text-and-fonts, pixels-and-images) and references/bcl-patterns/* (the .NET techniques), plus decision-framework.md (impact×complexity rubric + the two-proof gate), measuring.md, signals.md (detection routing), and repo-helpers.md. A lean SKILL.md routes between them. ~~ Benchmark harness readiness ~~ So a scan never wastes time repairing infra: replace TheBenchmark.cs — a trap whose [SimpleJob(Net48/Net70/Net80)] attributes silently skip off-Windows and whose empty bodies taught none of the conventions — with a working TemplateBenchmark.cs (New-vs-Old + [MemoryDiagnoser] + [Params] + return-sink that runs out of the box), and add benchmarks/README.md documenting the add/run commands, --list flat / --job short for fast iteration, the single-TFM rule, and the InternalsVisibleTo native-oracle pattern. ~~ Labels ~~ Findings are labelled tenet/performance plus one agent-chosen perf/* sub-type from the shared taxonomy in .agents/skills/issue-triage/references/labels.md (#4362), matching the memory-leak-fixer convention; the sub-type is decided by the win's dominant measured driver (a removed P/Invoke → perf/interop, removed allocations → perf/allocations, ...). ~~ Validated end to end ~~ The workflow self-tests on any PR touching the skill via a forced dry-run. Those runs correctly rejected a non-finding (SKFourByteTag's char[4] is already stack-allocated by .NET 9/10 escape analysis) and found real, fully-proven wins (SKShaper glyph-array extraction → perf/allocations; SKColor→SKColorF operator → perf/interop). A real dispatch run created a correctly-labelled issue (#4369) and draft PR (#4370), confirming the tenet/performance + perf/* labels land on both. No binding/runtime code changes: a new skill, a new workflow, benchmark docs/template, and two rows in AGENTS.md. Co-authored-by: Matthew Leibowitz <[email protected]> Co-authored-by: Copilot App <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description of Change
SKSurface.Canvaspreviously did real work on every access: a P/Invoke (sk_surface_get_canvas), a lockedHandleDictionarylookup (aReaderWriterLockSlimupgradeable-read lock), and anOwnedByConcurrentDictionaryregistration. In draw-heavy render loops that fetch the canvas per draw call, that overhead becomes a measurable bottleneck.This PR caches the managed
SKCanvaswrapper on the surface and reuses it across calls:The cache is dropped in
DisposeManagedso a disposed surface holds no stale wrapper.Why this is safe — Skia returns a stable canvas pointer for the surface's lifetime
The cache is only valid because Skia hands back the same
SkCanvas*for the life of the surface. Tracing the native call chain confirms this end-to-end.Our C shim (
externals/skia/src/c/sk_surface.cpp) is a straight pass-through:SkSurface::getCanvas()(src/image/SkSurface.cpp) delegates to the base class:And
SkSurface_Base::getCachedCanvas()(src/image/SkSurface_Base.h) lazily creates the canvas once and caches it —fCachedCanvasis assigned only inside the null-guard and is never reset or reassigned afterwards:Key consequences:
getCachedCanvas()lives inSkSurface_Base, so the guarantee holds for all backends (raster, Ganesh, Graphite, null).aboutToDraw/onCopyOnWrite) forks the device's backing store, but does not recreate theSkCanvas— the pointer is unaffected.fCachedCanvasmay point at a capture-wrapper canvas rather than the base canvas, but it is still set once and remains stable.Because the native pointer is stable, the managed wrapper keyed off it is stable too, so caching it is correct.
Edge case: explicit canvas disposal
Disposing the surface-owned canvas is an anti-pattern, but it must not leave the cache holding a dead wrapper. The wrapper is created with
owns: false, so disposing it does not callsk_canvas_destroy(the native canvas stays alive, owned by the surface) and it deregisters itself by identity fromHandleDictionary. Thecanvas.Handle == IntPtr.Zeroguard detects this and re-fetches a fresh, fully-functional wrapper around the still-alive native canvas.Performance
Per-getter cost drops from ~31 ns to ~0.67 ns (a field read + handle check), zero allocations; fetching
Canvasper draw now matches hand-caching it.Bugs Fixed
None — this is a performance optimization.
API Changes
None. (Adds a private field and a
protected override DisposeManaged; no public signatures change, so this is ABI-safe.)Behavioral Changes
SKSurface.Canvasnow returns a cached wrapper instead of re-resolving it on each access. Observable behavior is unchanged: the same instance was already returned before (viaHandleDictionary), and the wrapper's lifetime is still tied to the surface.HandleDictionarylock the old path incidentally took. This is benign under SkiaSharp's documented single-thread-per-surface model (a concurrent race resolves to the same instance), but it is a slight relaxation of the previous behavior.benchmarks/.../Program.csnow usesBenchmarkSwitcher, so running with no args shows a selection menu instead of auto-running a single benchmark. Select one with e.g.dotnet run -c Release -- --filter *SurfaceCanvasBenchmark*.Tests
CanvasReturnsSameInstanceAcrossCalls— guards that repeatedCanvasaccess returns the same instance/handle (regression guard).CanvasIsRefetchedAfterExplicitCanvasDispose— exercises the newHandle == IntPtr.Zerore-fetch path and verifies the re-fetched canvas is usable.Required skia PR
None.
PR Checklist