Skip to content

Optimize Cilbox interpreter allocations - #1037

Open
Toys0125 wants to merge 2 commits into
BasisVR:developerfrom
Toys0125:perf/cilbox-arraypool-lazy-copyback
Open

Optimize Cilbox interpreter allocations#1037
Toys0125 wants to merge 2 commits into
BasisVR:developerfrom
Toys0125:perf/cilbox-arraypool-lazy-copyback

Conversation

@Toys0125

@Toys0125 Toys0125 commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Reuse interpreter stack buffers through a private ArrayPool.
  • Clear pooled stack buffers when returned so managed references are released safely.
  • Avoid parameter-array allocations for zero-argument calls with Array.Empty().
  • Reuse a thread-static single-parameter buffer for the common one-argument case.
  • Preserve safe behavior for recursive/reentrant execution by falling back to a normal allocation when the cached parameter buffer is already in use.
  • Use Array.Empty() for zero-argument native calls.
  • Lazily allocate the native-call StackElement[] copyback buffer only when an argument is actually an Address or NativeHandle.
  • Skip the copyback loop entirely for normal native calls that cannot modify interpreter values by reference.
  • Performance

    Measured using 20 simultaneously active Fox Moth avatars running real Cilbox/Vixxy workloads.

    Metric origin/developer ArrayPool + lazy copyback
    Cilbox avg/frame 1098.364 µs 641.834 µs
    Cilbox P50 675.846 µs 532.836 µs
    Cilbox P95 1925.074 µs 1034.594 µs
    Per-proxy avg 54.918 µs 32.092 µs
    Per-proxy P95 96.254 µs 51.730 µs
    GC avg/frame 505,090 B 13,244 B
    GC P95/frame 522,622 B 26,302 B

    Required checks

    All boxes below must be ticked before this PR can merge. If a check is genuinely N/A, tick it anyway and explain under Notes.

    • Tested — I built and ran this locally. The change works in the editor and (where relevant) in a built player.
    • Transform access is combined and limited — In hot paths, transform reads/writes go through TransformAccessArray or are otherwise batched. I have not added per-frame transform.position / transform.rotation / transform.localPosition calls inside loops. Whenever I need both position and rotation, I use the combined APIs — SetPositionAndRotation / SetLocalPositionAndRotation for writes, GetPositionAndRotation / GetLocalPositionAndRotation for reads — instead of two separate property accesses; the combined call does one local-to-world matrix traversal instead of two.
    • Addressables used for asset/memory loading — Any new asset loads go through Addressables. No new Resources.Load, no direct asset references that pull large content into memory on scene load.
    • No new GetComponent / AddComponent where avoidable — Where unavoidable, the result is cached on a field, and any GetComponent<T> is replaced with TryGetComponent<T>(out var x) — bare GetComponent will be denied. TryGetComponent is the modern API (Unity 2019.2+) and skips the Editor-only GC allocation GetComponent causes when a component is missing: Unity wraps the null return in a managed "fake null" object so its overloaded == operator can still detect destroyed C++ objects, and constructing that wrapper allocates; TryGetComponent returns a bool plus out parameter and never builds the wrapper. None of these calls run inside Update, LateUpdate, FixedUpdate, jobs, or other per-frame code paths.
    • Per-frame work is scheduled through BasisEventDriver — Any new per-frame work hooks into BasisEventDriver rather than adding standalone Update / LateUpdate / FixedUpdate callbacks on a MonoBehaviour.
    • Anything added to BasisEventDriver is bulletproof, or guarded by try/catchBasisEventDriver runs the single per-frame tick that drives the whole framework (network apply, local player sim, blendshapes, JigglePhysics, nameplates, and more) as one sequential chain. An unhandled exception anywhere in that chain aborts the rest of the tick, so every step after the throwing one is silently skipped for that frame. New work added to the driver must either be guaranteed not to throw, or be wrapped in a try/catch that contains the failure and surfaces it through BasisDebug — logged once / rate-limited, never every frame (see the existing HVRBasisBuiltInAddresses.Simulate() guard for the pattern). Expect this to be scrutinized closely in review.
    • Considered jobification — I asked whether this work can be moved to a Unity Job (Burst-compiled where possible). If it can, it is. If it cannot, the reason is in Notes.
    • No needless { get; set; } properties or access lockdowns — Public fields are fine; Basis is meant to be read and modified freely, so don't wall things off private/internal without a real reason. Don't wrap a field in { get; set; } when the accessors do nothing — property accessors have a real performance cost vs direct field access, and the lead maintainer prefers plain fields (or a method / setter-only property when only the setter needs logic) over a noop-getter pair. For .Instance singletons, callers reassigning Type.Instance is allowed; if that would break your code, log a warning or throw — don't block the assignment. Locking down access is not your call.
    • Camera access goes through BasisLocalCameraDriver — Code that needs the local camera (transform, projection, rig data, etc.) pulls it from BasisLocalCameraDriver rather than looking one up itself. Don't roll a separate camera discovery path.
    • Logging uses BasisDebug — All new logging calls go through BasisDebug.Log / BasisDebug.LogWarning / BasisDebug.LogError (with an appropriate LogTag) instead of UnityEngine.Debug.Log / Debug.LogWarning / Debug.LogError. BasisDebug routes through Basis's tagged, color-coded logger and respects the project-wide LoggingDisabled toggle so logging can be killed at runtime; bare Debug.Log calls bypass that and will be denied.
    • No scene-wide discovery for dependencies — New code is architected so it does not need FindObjectOfType / FindObjectsOfType / GameObject.Find / FindGameObjectsWithTag to locate what it depends on. References are wired in — registered through an existing manager/driver, injected at init, or passed in by the caller — rather than discovered by scanning the scene at runtime. If a scene scan is genuinely unavoidable, justify it under Notes.
    • No allocations in hot paths — Per-frame code (Update / LateUpdate / FixedUpdate, simulation loops, jobs, anything called once per frame or more) does not allocate. No new on reference types, no LINQ, no string concatenation/interpolation, no boxing, no foreach over interface-typed collections. Allocate once at init and reuse the buffer.
    • No debugging in hot paths — No log calls of any kind on per-frame paths, including BasisDebug. Hot-path logging floods the console and incurs cost on every frame regardless of whether the message is filtered out downstream. If a hot-path log is needed while iterating, gate it behind #if UNITY_EDITOR and remove (or leave gated) before merge.
    • Hot-path collection access is optimized — Cache .Count (lists) / .Length (arrays) into a local int before the loop instead of re-reading the property each iteration. Prefer T[] (with a separate length int when the array is over-sized) over List<T> where the data is hot — Unity's mono BCL doesn't expose CollectionsMarshal.AsSpan(List<T>), so a list can't be fed into Span<T> / unsafe paths cleanly. Where the perf justifies it, drop into Span<T> / ref locals / Unsafe.As / unsafe pointer code to skip bounds checks and copies, and call out the invariants you're relying on under Notes so reviewers can sanity-check them.

    Testing details

    Tick the platforms you actually tested on. Leave the rest unticked — these are informational and do not block merge.

    • Windows
    • Linux
    • Android
    • iOS
    • macOS

    Input / control mode coverage:

    • Tested in VR (note headset under Notes)
    • Tested in desktop / non-VR mode
    • Tested with phone controls (mobile touch input)
    • N/A — change does not touch player/XR/input code

    Where applicable, confirm these flows still work after your changes:

    • Hot-switching (desktop ↔ VR mode swap at runtime)
    • Avatar swapping
    • Server swapping (joining / leaving / changing servers)
    • N/A — change does not touch any of the above

    Notes

    • Writing jobifiy would required to move the managed memory out of stack element.

@dooly123

dooly123 commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

i only accept changes to cilbox from upstream make sure it gets merged there and then i can merge.

@Toys0125

Toys0125 commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

Leaving notice for the Upstream PR cnlohr/cilbox#127

Co-authored-by: Error-mdl <20629398+Error-mdl@users.noreply.github.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.

2 participants