Skip to content

Avoid closure allocations in callback user-data storage - #5518

Open
mattleibow wants to merge 1 commit into
mainfrom
mattleibow-callback-allocation-cleanup
Open

mattleibow wants to merge 1 commit into
mainfrom
mattleibow-callback-allocation-cleanup

Conversation

@mattleibow

@mattleibow mattleibow commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Description

Remove capturing helper delegates from callback user-data storage shared by SkiaSharp and HarfBuzzSharp. Store user data directly in its GCHandle, and use a MultiUserData container to retain delegates and their declared type tokens instead of closure-based lookup.

The removed closures and helper delegates were allocated when creating callback contexts, not on each callback invocation. Multi-value contexts still allocate a MultiUserData container, and weak user-data contexts still allocate a WeakReference. This is not a claim that callback creation or invocation is allocation-free. No new benchmark was run, and no measured speedup or allocation-count claim is made here.

This PR targets main directly and is independent of the stream-correctness work in #5464. It does not need the former lower stream layers and is not registered in a native PR stack. Only binding/Binding.Shared/DelegateProxies.shared.cs changes (+76/-114): the exact implementation extracted from frozen #5479 (533564d4ac2859a025514a4e60831a5786c21dcf), with no redesign or additional changes. Direct GCHandle user-data storage, existing weak-reference semantics, declared delegate type tokens, and null-delegate lookup behavior are preserved as in that reviewed implementation.

No callback ABI, public signatures, exception policy, stream lifetime policy, stream correctness code, native pin, generated bindings, tests, or benchmarks are changed by this PR. Independent validation was performed in a fresh main-based checkout without importing the former stream-layer commits.

Related issues

Related to #5479 and #5464. Neither is a prerequisite for this allocation-only change beyond the code already present in main.

Required skia PR

None.

Areas affected

  • Managed API (binding/)
  • Native / C API (externals/skia/src/c, include/c)
  • Generated P/Invoke bindings
  • Native dependency or Skia update (libpng, HarfBuzz, FreeType, zlib, milestone bump, …)
  • Views & integrations (MAUI, Uno, WPF, WinUI, Blazor, …)
  • Rendering output / visual behavior
  • Performance
  • Tests
  • Build, packaging, or CI
  • Documentation or samples

Changes

None. No public API, callback ABI, rendering, exception-policy, or lifetime-policy changes; this PR only changes internal callback context storage to avoid capturing helper delegates.

Testing

Named independently tested snapshot 49358d0a30d162cb0208f4d190930e3dc12ac2b2, based directly on main commit 7b0b03819c9c1cd22ca8403ced9859f9f5cfe565, passed in a fresh isolated macOS ARM64 checkout. Exactly one allocation commit sits above that baseline; no stream-correctness layer was imported. Exact HEAD/branch and clean-worktree checks passed before and after each command:

  • dotnet build binding/SkiaSharp/SkiaSharp.csproj --verbosity quiet — passed, zero errors and four warnings; all 13 normally configured TFMs, including net48, with no framework overrides.
  • dotnet build binding/HarfBuzzSharp/HarfBuzzSharp.csproj --verbosity quiet — passed, zero errors and four warnings; all 13 normally configured TFMs, including net48, with no framework overrides.
  • dotnet build tests/SkiaSharp.Tests.Console.slnx -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 --no-incremental --verbosity quiet — passed, zero errors and 58 warnings; rebuilt the test hosts before native-copy verification and execution.
  • dotnet test tests/SkiaSharp.Tests.Console.slnx -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 — passed unfiltered: 6,532 passed, 47 existing platform/capability skips, zero failed. Core: 6,475 passed / 23 skipped; singleton: 1 / 0; gallery: 50 / 0; Vulkan: 4 / 21; Direct3D: 2 / 3.
  • git range-diff --no-color 887187f375a815fa54097e5dcd101cb2b0c68bd0..25c982d11e64c993a166392223b60c0473edac38 7b0b03819c9c1cd22ca8403ced9859f9f5cfe565..49358d0a30d162cb0208f4d190930e3dc12ac2b2 — passed: the extracted allocation patch is unchanged. Its committed binary diff is byte-identical to the frozen original one-file patch; resulting source blob 37985b79479c40506255834df3a4cf5490ba023a, patch SHA256 3e54b2368b0285dd058212375b1138ac44aec7412ceaa3eb4a8e5da02ba9e453.

Used source-matched macOS native assets from Azure DevOps main build 1655687, source b45912c193582b20664445e506e92f773a1aa6e8, Skia pin 748bc0c0116c3952f0a0089f5cc53edc55ae08de (m156). Native pins, version inputs, and externals were verified unchanged on the tested main baseline. Verified archive SHA256 e78c31c215234b264a7c1cde97f6ce082488d076fe7911021baad4ff4a7bdd41, extracted only the two named regular dylibs, and checked their hashes in all five test-host output directories before and after execution. SkiaSharp SHA256: c7ff59007830d44a91f08d24ae3120de1e6e43d921a5b4f3c525346d7648097e; HarfBuzzSharp SHA256: dd6f10d2c051dac3623c8af2adde87307e728569b862b7e1d15d0c75f6ff9e17.

The results above refer to the named independent snapshot, not to an old stacked snapshot or a floating head. No tests, benchmark tooling, refactors, or skip-policy changes were added. Existing tests were used to validate the exact extracted implementation. Runtime execution on other platforms/TFMs was not performed. No rendering change or golden-image update is expected.

Checklist

  • Tests added or updated (if omitted, explain why above)
  • Changes above lists all public API and behavioral changes (or "None.")
  • New/changed public API? Added or updated accurate source /// documentation and regenerated bindings when applicable
  • Native change? Companion mono/skia PR linked above and bindings regenerated

@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 -- 5518

PowerShell / Windows:

iex "& { $(irm https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.ps1) } 5518"

Step 2 — Add the local NuGet source

dotnet nuget add source ~/.skiasharp/hives/pr-5518/packages --name skiasharp-pr-5518
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-5518

@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

📊 SkiaSharp benchmarks — PR #5518

⭐ this PR (full source build) vs 🌙 nightly · Linux · Windows · macOS

Informational only — this never blocks the PR. 🟢 faster / less allocation · 🔴 slower / more allocation; moves under 5% are hidden as noise.

⏱️ Times are raw BenchmarkDotNet means, and the ⭐ PR and baseline legs run on separate CI runners, so microbenchmarks can swing run-to-run — treat small time deltas as noise. Allocations are deterministic and the reliable signal. The interactive perf-dashboard (linked below) applies smoothing for the trend view.

Highlights

⏱️ Time — 🔴 40 slower · 🟢 24 faster

  • 🔴 MatrixMapPointsBenchmark.MapRadius(Points: 256) · Windows · 8.45 µs → 11.91 µs (+41%)
  • 🔴 PathBoundsBenchmark.TightBounds(Points: 1024) · Windows · 15.33 µs → 21.27 µs (+39%)
  • 🔴 RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) · Windows · 96.08 µs → 127.92 µs (+33%)
  • 🔴 MatrixMapPointsBenchmark.MapRadius(Points: 4096) · Windows · 136.22 µs → 181.03 µs (+33%)
  • 🔴 MatrixOpsBenchmark.Concat(Count: 4096) · Windows · 215.95 µs → 277.82 µs (+29%)
  • …and 59 more (see details below)
Full per-OS benchmark deltas

Linux

⏱️ Time (vs 🌙 nightly 4.156.0-nightly.26529.13)

Benchmark baseline this PR Δ
ColorMathBenchmark.ToColor(Colors: 4096) 15.42 µs 19.04 µs 🔴 +23%
MatrixOpsBenchmark.Concat(Count: 4096) 257.32 µs 216.32 µs 🟢 -16%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 100.01 µs 109.04 µs 🔴 +9%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 11.46 µs 12.12 µs 🔴 +6%

Windows

⏱️ Time (vs 🌙 nightly 4.156.0-nightly.26529.13)

Benchmark baseline this PR Δ
MatrixMapPointsBenchmark.MapRadius(Points: 256) 8.45 µs 11.91 µs 🔴 +41%
PathBoundsBenchmark.TightBounds(Points: 1024) 15.33 µs 21.27 µs 🔴 +39%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 96.08 µs 127.92 µs 🔴 +33%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 136.22 µs 181.03 µs 🔴 +33%
MatrixOpsBenchmark.Concat(Count: 4096) 215.95 µs 277.82 µs 🔴 +29%
PathBoundsBenchmark.TightBounds(Points: 64) 1.52 µs 1.95 µs 🔴 +28%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 122.22 µs 147.30 µs 🔴 +21%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 252.52 µs 303.77 µs 🔴 +20%
MatrixOpsBenchmark.Invert(Count: 4096) 128.55 µs 154.23 µs 🔴 +20%
MatrixMapPointsBenchmark.MapRect(Points: 4096) 167.08 µs 197.87 µs 🔴 +18%
MatrixMapPointsBenchmark.MapRect(Points: 256) 10.68 µs 12.50 µs 🔴 +17%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 1.22 ms 1.42 ms 🔴 +16%
MatrixMapPointsBenchmark.MapVector(Points: 256) 8.32 µs 9.58 µs 🔴 +15%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 2.64 µs 2.99 µs 🔴 +13%
ColorMathBenchmark.PreMultiply(Colors: 4096) 12.98 µs 14.68 µs 🔴 +13%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 11.53 µs 13.03 µs 🔴 +13%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 244.40 µs 273.49 µs 🔴 +12%
ColorMathBenchmark.ToColor(Colors: 4096) 14.45 µs 16.14 µs 🔴 +12%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 323.28 µs 360.30 µs 🔴 +11%
ColorParseBenchmark.Parse(Iterations: 1000) 77.64 µs 86.32 µs 🔴 +11%
RuntimeEffectShaderBenchmark.DrawFrame 1.13 ms 1.26 ms 🔴 +11%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 912.79 µs 1.01 ms 🔴 +11%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 2.89 ms 3.19 ms 🔴 +11%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 741.90 µs 808.48 µs 🔴 +9%
CanvasDrawBenchmark.Draw(Shapes: 64) 2.65 ms 2.87 ms 🔴 +9%
…and 7 more

macOS

⏱️ Time (vs 🌙 nightly 4.156.0-nightly.26529.13)

Benchmark baseline this PR Δ
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 3.41 ms 2.66 ms 🟢 -22%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 1.83 ms 1.43 ms 🟢 -22%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 286.90 µs 225.28 µs 🟢 -21%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 222.82 µs 176.28 µs 🟢 -21%
ColorParseBenchmark.Parse(Iterations: 1000) 83.75 µs 66.41 µs 🟢 -21%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 55.70 µs 44.55 µs 🟢 -20%
ColorMathBenchmark.ToColor(Colors: 4096) 24.65 µs 19.93 µs 🟢 -19%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 7.07 ms 5.73 ms 🟢 -19%
MatrixMapPointsBenchmark.MapRect(Points: 4096) 75.74 µs 62.23 µs 🟢 -18%
ColorMathBenchmark.ToColorF(Colors: 4096) 6.20 µs 5.11 µs 🟢 -18%
MatrixOpsBenchmark.Concat(Count: 4096) 147.00 µs 121.56 µs 🟢 -17%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 170.4 ns 144.8 ns 🟢 -15%
PathBoundsBenchmark.TightBounds(Points: 64) 1.18 µs 1.01 µs 🟢 -14%
ColorMathBenchmark.PreMultiply(Colors: 4096) 9.73 µs 8.34 µs 🟢 -14%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 907.99 µs 1.03 ms 🔴 +14%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 793.36 µs 685.27 µs 🟢 -14%
MatrixMapPointsBenchmark.MapVector(Points: 256) 2.51 µs 2.82 µs 🔴 +13%
MatrixOpsBenchmark.Invert(Count: 4096) 81.62 µs 71.61 µs 🟢 -12%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 130.43 µs 116.04 µs 🟢 -11%
CanvasDrawBenchmark.Draw(Shapes: 512) 13.43 ms 11.99 ms 🟢 -11%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 732.99 µs 809.78 µs 🔴 +10%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 8.40 µs 7.55 µs 🟢 -10%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 1.26 µs 1.15 µs 🟢 -9%
SceneRenderBenchmark.RenderFrame(Complexity: 4) 6.10 ms 6.61 ms 🔴 +8%
MatrixMapPointsBenchmark.MapRect(Points: 256) 3.23 µs 3.00 µs 🟢 -7%
…and 3 more

📈 Full interactive perf-dashboard & run details →

mattleibow added a commit that referenced this pull request Oct 30, 2026
…cks (#5479)

Use blittable Byte for C bool and Int32 for hb_bool_t delegate callbacks (#5479)

Context: dotnet/runtime#136578
Context: #5464
Context: #5518

Match generated unmanaged callback delegates, function pointers, and
DelegateProxies implementations to their native C ABI boolean widths by using
1-byte Byte for Skia C/C++ bool and 4-byte Int32 for HarfBuzz hb_bool_t, while
keeping public managed delegate and API signatures on bool.

~~ Use 1-byte Byte for Skia C/C++ bool callbacks ~~

SkiaSharpGenerator mapped C bool to Byte for struct fields, but overrode
callback parameters and returns back to bool with [MarshalAs(UnmanagedType.I1)].
[UnmanagedCallersOnly] and delegate* unmanaged[Cdecl] ignore [MarshalAs], and
the Mono ARM64 interpreter (dotnet/runtime#136578) does not zero-extend bool
returns across the 32-bit return register expected by Apple ARM64 C++ callers.

Map C bool to Byte in GetManagedFunctionArguments and GetFunctionPointerType
(BaseTool.cs), remove [return: MarshalAs(UnmanagedType.I1)] from WriteDelegate
and WriteDelegateProxy (Generator.cs), and update the Skia stream, write-stream,
and Graphite image-provider proxy implementations to convert between byte and
bool. Forward P/Invoke declarations in WriteFunctions keep
[MarshalAs(UnmanagedType.I1)] bool.

~~ Use 4-byte Int32 for HarfBuzz hb_bool_t callbacks ~~

HarfBuzz defines typedef int hb_bool_t; (4 bytes), which libHarfBuzzSharp.json
maps to "Boolean". Treating "Boolean" the same as C bool generated 1-byte I1 or
unmarshaled bool returns instead of 4-byte int callbacks.

Map "Boolean" to Int32 for callback delegates and function pointers, update the
HarfBuzz font and Unicode proxy implementations to return 1 or 0, and return 0
immediately in FontGetGlyphNameProxyImplementation before copying the name span
when GlyphNameDelegate returns false. HBFontFuncsTest and HBUnicodeFuncsTest
verify false-returning callbacks.

Co-authored-by: Matthew Leibowitz <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Alex Soto <[email protected]>
@mattleibow
mattleibow force-pushed the mattleibow-callback-allocation-cleanup branch from f23fb2d to 1be958c Compare October 30, 2026 14:37
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from 1b4815a to f213039 Compare October 30, 2026 15:04
@mattleibow
mattleibow force-pushed the mattleibow-callback-allocation-cleanup branch from 1be958c to 27b1edf Compare October 30, 2026 15:05
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from f213039 to 5d22a24 Compare October 30, 2026 15:39
@mattleibow
mattleibow force-pushed the mattleibow-callback-allocation-cleanup branch from 27b1edf to d368194 Compare October 30, 2026 15:42
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from 5d22a24 to 67e9769 Compare October 30, 2026 16:59
@mattleibow
mattleibow force-pushed the mattleibow-callback-allocation-cleanup branch from d368194 to 24d23ad Compare October 30, 2026 17:04
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch 2 times, most recently from 2339d6a to ef410c8 Compare October 30, 2026 20:01
@mattleibow
mattleibow force-pushed the mattleibow-callback-allocation-cleanup branch from 24d23ad to e0d0911 Compare October 30, 2026 20:03
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from ef410c8 to eac144a Compare October 30, 2026 20:25
@mattleibow
mattleibow force-pushed the mattleibow-callback-allocation-cleanup branch from e0d0911 to c83fc51 Compare October 30, 2026 20:27
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from eac144a to 3cc669d Compare October 30, 2026 21:10
@mattleibow
mattleibow force-pushed the mattleibow-callback-allocation-cleanup branch from c83fc51 to 73d502f Compare October 30, 2026 21:14
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from 3cc669d to 887187f Compare October 31, 2026 00:26
@mattleibow
mattleibow force-pushed the mattleibow-callback-allocation-cleanup branch from 73d502f to 25c982d Compare October 31, 2026 00:29
@mattleibow
mattleibow removed this pull request from stack #5513 October 31, 2026 00:51
Store user data directly in GCHandles and use a MultiUserData container for delegate lookup instead of allocating capturing helper delegates. Preserve weak-reference storage and declared delegate type tokens, including null delegates.

Extract only DelegateProxies.shared.cs from the frozen callback work so this managed allocation cleanup can ship independently of the callback ABI and stream safety changes.

Co-authored-by: Copilot App <[email protected]>
@mattleibow
mattleibow force-pushed the mattleibow-callback-allocation-cleanup branch from 25c982d to 49358d0 Compare October 31, 2026 01:12
@mattleibow
mattleibow changed the base branch from mattleibow-fix-front-buffered-streams to main October 31, 2026 01:13
@mattleibow

Copy link
Copy Markdown
Contributor Author

@dalexsoto review

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.

🟢 Approval recommended

There are no active review issues for the callback-context storage refactor.

No open issues 🎉

What changed in this PR

This PR changes internal callback-context storage shared by SkiaSharp and HarfBuzzSharp to remove capturing helper delegates. It is separate from the stream-correctness work and leaves public signatures and callback ABI unchanged.

Changes:

  • Stores user data directly in a GCHandle, retaining weak-reference unwrapping.
  • Replaces closure-based multi-delegate lookup with a MultiUserData container that preserves declared delegate types and null-delegate lookup behavior.
File Description
binding/​Binding.Shared/​DelegateProxies.shared.cs Replaces closure-based callback storage with direct user-data storage and a typed multi-delegate container.

Review effort: Balanced

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed the complete changed delegate-context implementation and affected SkiaSharp/HarfBuzz callback producers, consumers, rooting/release paths, generated entry-point branches, compilation conditions and relevant existing tests, including a separate final search for independent blockers.

The allocation-only extraction preserves the reviewed weak-reference lifetime, declared delegate-type and optional-null-delegate handling, and callback contracts. No high-confidence blocking issue remains in this bounded static review. No build/test execution, generated-output regeneration or native-archive certification is claimed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Approved

Development

Successfully merging this pull request may close these issues.

4 participants