Skip to content

perf(SKSurface): cache the Canvas wrapper across calls - #4247

Merged
mattleibow merged 1 commit into
mono:mainfrom
ramezgerges:dev/cache-surface-canvas
Jun 26, 2026
Merged

mattleibow merged 1 commit into
mono:mainfrom
ramezgerges:dev/cache-surface-canvas

Conversation

@ramezgerges

@ramezgerges ramezgerges commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Description of Change

SKSurface.Canvas previously did real work on every access: a P/Invoke (sk_surface_get_canvas), a locked HandleDictionary lookup (a ReaderWriterLockSlim upgradeable-read lock), and an OwnedBy ConcurrentDictionary registration. In draw-heavy render loops that fetch the canvas per draw call, that overhead becomes a measurable bottleneck.

This PR caches the managed SKCanvas wrapper on the surface and reuses it across calls:

public SKCanvas Canvas {
    get {
        // Re-fetch if not yet cached, or if the cached wrapper was disposed out from
        // under us (e.g. a caller explicitly disposed the surface-owned canvas).
        if (canvas == null || canvas.Handle == IntPtr.Zero) {
            canvas = OwnedBy (SKCanvas.GetObject (SkiaApi.sk_surface_get_canvas (Handle), false, unrefExisting: false), this);
        }
        GC.KeepAlive (this);
        return canvas;
    }
}

The cache is dropped in DisposeManaged so 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:

sk_canvas_t* sk_surface_get_canvas(sk_surface_t* csurf) {
    return ToCanvas(AsSurface(csurf)->getCanvas());
}

SkSurface::getCanvas() (src/image/SkSurface.cpp) delegates to the base class:

SkCanvas* SkSurface::getCanvas() {
    return asSB(this)->getCachedCanvas();
}

And SkSurface_Base::getCachedCanvas() (src/image/SkSurface_Base.h) lazily creates the canvas once and caches it — fCachedCanvas is assigned only inside the null-guard and is never reset or reassigned afterwards:

SkCanvas* SkSurface_Base::getCachedCanvas() {
    if (nullptr == fCachedCanvas) {
        fOwnedBaseCanvas = std::unique_ptr<SkCanvas>(this->onNewCanvas());
        if (fOwnedBaseCanvas) {
            fOwnedBaseCanvas->setSurfaceBase(this);
        }
        // Try to wrap base canvas in capture wrapper
        if (this->baseRecorder()) {
            fCachedCanvas = this->baseRecorder()->makeCaptureCanvas(fOwnedBaseCanvas.get());
        }
        if (!fCachedCanvas) {
            fCachedCanvas = fOwnedBaseCanvas.get();
        }
    }
    return fCachedCanvas;
}

Key consequences:

  • getCachedCanvas() lives in SkSurface_Base, so the guarantee holds for all backends (raster, Ganesh, Graphite, null).
  • Copy-on-write (aboutToDraw / onCopyOnWrite) forks the device's backing store, but does not recreate the SkCanvas — the pointer is unaffected.
  • With a capture recorder, fCachedCanvas may 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 call sk_canvas_destroy (the native canvas stays alive, owned by the surface) and it deregisters itself by identity from HandleDictionary. The canvas.Handle == IntPtr.Zero guard 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 Canvas per draw now matches hand-caching it.

Note: the in-repo SurfaceCanvasBenchmark compares "fetch per draw" vs. "cache per frame" within a single build. Because this PR makes the getter cheap, those two converge on the patched branch — the improvement is an A/B comparison against the baseline commit. FetchCanvasNoDraw best isolates the raw getter cost.

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.Canvas now returns a cached wrapper instead of re-resolving it on each access. Observable behavior is unchanged: the same instance was already returned before (via HandleDictionary), and the wrapper's lifetime is still tied to the surface.
  • Threading note: the cache field is read/written without the HandleDictionary lock 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.cs now uses BenchmarkSwitcher, 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 repeated Canvas access returns the same instance/handle (regression guard).
  • CanvasIsRefetchedAfterExplicitCanvasDispose — exercises the new Handle == IntPtr.Zero re-fetch path and verifies the re-fetched canvas is usable.

Required skia PR

None.

PR Checklist

  • Has tests
  • Rebased on top of main at time of PR
  • Merged related skia PRs
  • Changes adhere to coding standard
  • Updated documentation

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]>
@github-actions

Copy link
Copy Markdown
Contributor

📦 Try the packages from this PR

Warning

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 -- 4247

PowerShell / 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-4247
More options
Option Description
--successful-only / -SuccessfulOnly Only use successful builds
--force / -Force Overwrite previously downloaded packages
--list / -List List available artifacts without downloading
--build-id ID / -BuildId ID Download from a specific build

Or download manually from Azure Pipelines — look for the nuget artifact on the build for this PR.

Remove the source when you're done:

dotnet nuget remove source skiasharp-pr-4247

@dotnet-policy-service

Copy link
Copy Markdown
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.

@mattleibow

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

@mattleibow
mattleibow merged commit 0d83945 into mono:main Jun 26, 2026
6 checks passed
@mattleibow mattleibow added the tenet/performance Performance related issues label Jun 26, 2026
@mattleibow mattleibow added this to the 4.150.0-preview.3 milestone Jun 26, 2026
@ramezgerges
ramezgerges deleted the dev/cache-surface-canvas branch June 29, 2026 14:18
@mattleibow mattleibow modified the milestones: 4.150.0-preview.3, 4.150.0-rc.1 Jun 29, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community ✨ tenet/performance Performance related issues

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants