# Persistant arrays (or parameters) to avoid re-allocation

**URL:** https://discourse.julialang.org/t/persistant-arrays-or-parameters-to-avoid-re-allocation/60889
**Category:** General Usage
**Created:** [May 10, 2021, 1:48pm UTC](https://discourse.julialang.org/t/persistant-arrays-or-parameters-to-avoid-re-allocation/60889 "2021-05-10T13:48:41Z")
**Posts on this page:** 1
**Showing post:** 4

<div class="post-metadata">

### Author: ![fabiangans](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fabiangans/32/2624_2.png) [@fabiangans](https://discourse.julialang.org/u/fabiangans)
#### Post date: [May 10, 2021, 6:31pm UTC](https://discourse.julialang.org/t/persistant-arrays-or-parameters-to-avoid-re-allocation/60889/4 "2021-05-10T18:31:51Z")

</div>

I personally would prefer your option 3:

> Create a structure with all the intermediate parameters and then using the structure as a callable function (call overloading). But I don’t really how the boilerplate can be done (without init here in the parent function) (see [Emulate local static variable?](https://discourse.julialang.org/t/emulate-local-static-variable/956))

It stores the persistent arrays in a transparent manner and leads to nice code. The boilerplate could look like this:

```julia
using FFTW, LinearAlgebra
struct preAllocatedSquareModulusFFT{T,P,U}
   absout::Vector{T} 
   planFFT::P
   internal::Vector{U}
end
function preAllocatedSquareModulusFFT(sig)
    abs_out = zeros(eltype(real(sig)),length(sig)); 
    planFFT = plan_fft(copy(sig);flags=FFTW.PATIENT);
    internal = similar(sig)
    preAllocatedSquareModulusFFT(abs_out, planFFT, internal)
end

function (f::(preAllocatedSquareModulusFFT))(x)
    nbSamples = length(x)
    # --- Compute FFT 
    mul!(f.internal,f.planFFT,x) # This is a FFT
    # --- Abs2 
    for i in 1:1:nbSamples # Can be even faster with @avx and @inbounds but not the topic here :)
        f.absout[i] = abs2(f.internal[i])
    end
    return f.absout
end

```

You would then call the function as follows:

```julia
N = 1024
sig = randn(Complex{Float64},N)

# Create the struct once
f = preAllocatedSquareModulusFFT(sig) 

# And call (multiple times)
f(sig)

```

---

_[View the full topic](https://discourse.julialang.org/t/persistant-arrays-or-parameters-to-avoid-re-allocation/60889)._
