# Reusing preallocated memory without unsafe wraps

**URL:** <https://discourse.julialang.org/t/reusing-preallocated-memory-without-unsafe-wraps/77069>\
**Category:** Performance\
**Tags:** multithreading, memory, memory-allocation\
**Created:** [February 25, 2022, 2:01pm UTC](https://discourse.julialang.org/t/reusing-preallocated-memory-without-unsafe-wraps/77069 "2022-02-25T14:01:04Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![PeterSimon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/petersimon/32/25193_2.png) [@PeterSimon](https://discourse.julialang.org/u/PeterSimon)\
**Post date:** [February 25, 2022, 10:05pm UTC](https://discourse.julialang.org/t/reusing-preallocated-memory-without-unsafe-wraps/77069/6 "2022-02-25T22:05:27Z")

</div>

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

```julia
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

```

---

_[View the full topic](https://discourse.julialang.org/t/reusing-preallocated-memory-without-unsafe-wraps/77069)._
