Every call allocates a temporary buffer #11

Closed
opened 2026-10-23 12:48:15 +01:00 by pedro-bento · 1 comment
Owner

Summary

Wrappers that pass a struct by pointer allocate a one-element FFI array on every call. Wrappers
that accept an array allocate a copy on every call. In per-pixel and per-frame code this creates
constant garbage and GC pauses.

Current behavior

function M.UpdateCamera(camera, mode)          -- once per frame
  local _o1 = ffi.new("Camera[1]", camera)
  C.UpdateCamera(_o1, mode)
  return _o1[0]
end

There are 71 such sites. 57 wrap an Image, and the ImageDraw* family runs inside per-pixel
loops — one allocation per pixel.

Array conversion adds a second problem:

if type(points) == "table" then _a1 = to_array("Vector2", points) end

38 conversions copy every element into a fresh array. A 1000-point strip at 60 FPS is 16 KB of
garbage and 1000 struct copies per second per strip. The JIT cannot optimise the allocation away.

Proposal

1. Reuse one struct slot per type

local slots, depth = {}, {}

local function slot(ct)
  local d = (depth[ct] or 0) + 1
  depth[ct] = d
  local list = slots[ct] or {}
  slots[ct] = list
  local b = list[d] or ffi.new(ct .. "[1]")
  list[d] = b
  return b, d
end

Generated wrapper:

function M.UpdateCamera(camera, mode)
  local _o, _d = slot("Camera")
  _o[0] = camera
  C.UpdateCamera(_o, mode)
  local result = _o[0]
  unslot("Camera", _d)
  return result
end

The depth counter makes re-entry safe when a callback calls another wrapper during a C call. The
normal path is depth 1, so the allocation happens once per type for the process lifetime.

2. Skip the copy-out for image draws

ImageDraw* and ImageClearBackground change pixels, not the Image fields. Return the input
instead of _o[0]. Everything else keeps the copy-out, because it may change width, height,
format or data.

Match by function-name prefix with an explicit list, defaulting to "copy":

local NO_FIELD_WRITE = { ImageDraw = true, ImageClearBackground = true }

3. Reuse array buffers

Keep one buffer per type and depth, growing to the high-water mark and never shrinking:

function M.DrawLineStrip(points, pointCount, color)
  if type(points) ~= "table" then
    return C.DrawLineStrip(points, pointCount, color)   -- cdata: no copy, unchanged
  end
  local a, ct, d = to_array("Vector2", points, pointCount)
  C.DrawLineStrip(a, pointCount or #points, color)
  if ct then unarray(ct, d) end
end

Rules:

  • Only cache when the callee does not keep the pointer. All 38 current sites read during the call;
    add a RETAINS_PTR list for exceptions and re-audit it on every raylib bump.
  • Cap the buffer at 1 MiB. File-sized payloads allocate fresh and are not cached.
  • Never hand the cached buffer to Lua; the next call at the same depth overwrites it.
  • n == 0 passes nil and allocates nothing.

4. Document the fast path

Passing a cdata array already skips conversion. Users who care can allocate once:

local pts = ffi.new("Vector2[?]", n)

Do not add per-element helper closures; they cost more than the array.

What stays the same

  • Structs returned by value (GetMousePosition) allocate one cdata per call. They are
    user-visible values, so caching them would be wrong.
  • M.C remains the escape hatch.

Acceptance criteria

  • UpdateCamera 200 000 times with GC stopped grows memory by less than 4 KiB.
  • ImageDrawPixel 1 000 000 times shows no per-call garbage.
  • DrawLineStrip with 1000 points, 10 000 times, allocates only on the first call.
  • Results match the old code for every converted wrapper.
  • make check-bindings passes.

Notes

  • Memory is bounded by types × depth × high-water mark, a few hundred KB in practice.
  • Wrappers never yield, so per-type depth is safe across coroutines.
## Summary Wrappers that pass a struct by pointer allocate a one-element FFI array on every call. Wrappers that accept an array allocate a copy on every call. In per-pixel and per-frame code this creates constant garbage and GC pauses. ## Current behavior ```lua function M.UpdateCamera(camera, mode) -- once per frame local _o1 = ffi.new("Camera[1]", camera) C.UpdateCamera(_o1, mode) return _o1[0] end ``` There are 71 such sites. 57 wrap an `Image`, and the `ImageDraw*` family runs inside per-pixel loops — one allocation per pixel. Array conversion adds a second problem: ```lua if type(points) == "table" then _a1 = to_array("Vector2", points) end ``` 38 conversions copy every element into a fresh array. A 1000-point strip at 60 FPS is 16 KB of garbage and 1000 struct copies per second per strip. The JIT cannot optimise the allocation away. ## Proposal ### 1. Reuse one struct slot per type ```lua local slots, depth = {}, {} local function slot(ct) local d = (depth[ct] or 0) + 1 depth[ct] = d local list = slots[ct] or {} slots[ct] = list local b = list[d] or ffi.new(ct .. "[1]") list[d] = b return b, d end ``` Generated wrapper: ```lua function M.UpdateCamera(camera, mode) local _o, _d = slot("Camera") _o[0] = camera C.UpdateCamera(_o, mode) local result = _o[0] unslot("Camera", _d) return result end ``` The depth counter makes re-entry safe when a callback calls another wrapper during a C call. The normal path is depth 1, so the allocation happens once per type for the process lifetime. ### 2. Skip the copy-out for image draws `ImageDraw*` and `ImageClearBackground` change pixels, not the `Image` fields. Return the input instead of `_o[0]`. Everything else keeps the copy-out, because it may change `width`, `height`, `format` or `data`. Match by function-name prefix with an explicit list, defaulting to "copy": ```lua local NO_FIELD_WRITE = { ImageDraw = true, ImageClearBackground = true } ``` ### 3. Reuse array buffers Keep one buffer per type and depth, growing to the high-water mark and never shrinking: ```lua function M.DrawLineStrip(points, pointCount, color) if type(points) ~= "table" then return C.DrawLineStrip(points, pointCount, color) -- cdata: no copy, unchanged end local a, ct, d = to_array("Vector2", points, pointCount) C.DrawLineStrip(a, pointCount or #points, color) if ct then unarray(ct, d) end end ``` Rules: - Only cache when the callee does not keep the pointer. All 38 current sites read during the call; add a `RETAINS_PTR` list for exceptions and re-audit it on every raylib bump. - Cap the buffer at 1 MiB. File-sized payloads allocate fresh and are not cached. - Never hand the cached buffer to Lua; the next call at the same depth overwrites it. - `n == 0` passes `nil` and allocates nothing. ### 4. Document the fast path Passing a cdata array already skips conversion. Users who care can allocate once: ```lua local pts = ffi.new("Vector2[?]", n) ``` Do not add per-element helper closures; they cost more than the array. ## What stays the same - Structs returned by value (`GetMousePosition`) allocate one cdata per call. They are user-visible values, so caching them would be wrong. - `M.C` remains the escape hatch. ## Acceptance criteria - [ ] `UpdateCamera` 200 000 times with GC stopped grows memory by less than 4 KiB. - [ ] `ImageDrawPixel` 1 000 000 times shows no per-call garbage. - [ ] `DrawLineStrip` with 1000 points, 10 000 times, allocates only on the first call. - [ ] Results match the old code for every converted wrapper. - [ ] `make check-bindings` passes. ## Notes - Memory is bounded by types × depth × high-water mark, a few hundred KB in practice. - Wrappers never yield, so per-type depth is safe across coroutines.
Author
Owner

#15

https://git.pbento.pt/pedro-bento/hate-no-d/pulls/15
Sign in to join this conversation.
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference: pedro-bento/hate-no-d#11
No description provided.