Reusing preallocated memory without unsafe wraps

I may be missing something obvious, but it seems to me that a straightforward solution would be along these lines…

buffer = zeros(1_000_000)  # As large as needed for maximal case
function makemat(buffer::AbstractVector, m, n)
    mn = m*n
    mn ≤ length(buffer) || error("buffer size exceeded")
    mymat = reshape(view(buffer, 1:mn), m, n)
end

using BenchmarkTools
x = rand(30)
a = rand(30, 30)
b = makemat(buffer, 30, 30)
b .= a

@btime $a*$x  # 176.366 ns (1 allocation: 304 bytes)
@btime $b*$x  # 178.700 ns (1 allocation: 304 bytes)

nothing
2 Likes