Skip to content

(feat): add reshape! — zero-allocation array reshaping via pool wrapper cache#21

Merged
mgyoo86 merged 5 commits intomasterfrom
feat/reshape!
Mar 6, 2026
Merged

(feat): add reshape! — zero-allocation array reshaping via pool wrapper cache#21
mgyoo86 merged 5 commits intomasterfrom
feat/reshape!

Conversation

@mgyoo86
Copy link
Member

@mgyoo86 mgyoo86 commented Mar 6, 2026

Summary

Add reshape!(pool, A, dims...) that reshapes arrays using the pool's N-D wrapper cache. On Julia 1.11+, cross-dimensional reshapes are zero-allocation after warmup via setfield!-based wrapper reuse. The result shares memory with the source array.

Motivation

Base.reshape allocates a new wrapper object on every call (~40-80 bytes). In hot loops that repeatedly reshape pooled arrays (e.g., treating a flat vector as a matrix for BLAS), these wrapper allocations accumulate. reshape! eliminates this by reusing cached wrappers from the pool's existing nd_wrappers infrastructure.

Changes

File Change
src/acquire.jl Add _claim_slot! (wrapper-only slot reservation) and _reshape_impl! for AdaptiveArrayPool using setfield!(:ref, :size)
src/convenience.jl Add public reshape! API with _record_type_touch!, DisabledPool fallbacks, and _impl! delegators
src/macros.jl Transform reshape!_reshape_impl! inside @with_pool/@maybe_with_pool; extract eltype(A) for typed-lazy mode
docs/ API docs, quick-start example, and reference table entry
test/test_reshape.jl 427-line test suite (see below)

Design

  • Same dimensionality (M == N): setfield!(A, :size, dims) in-place — no pool interaction, effectively free
  • Cross dimensionality (M != N): _claim_slot! reserves a pool slot without backing memory, then reuses a cached Array{T,N} wrapper via setfield!(:ref, :size) pointing to A's MemoryRef
  • Memory sharing: Reshaped array shares memory with original — mutations visible in both directions
  • Validation: DimensionMismatch thrown before slot reservation if prod(dims) != length(A)
  • Julia 1.10 fallback: Base _reshape_impl! delegates to Base.reshape

Loading
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