# Filling a preallocated array without allocations

**URL:** <https://discourse.julialang.org/t/filling-a-preallocated-array-without-allocations/26896>\
**Category:** Performance\
**Created:** [July 28, 2019, 1:41am UTC](https://discourse.julialang.org/t/filling-a-preallocated-array-without-allocations/26896 "2019-07-28T01:41:02Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![guilhermebodin](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/guilhermebodin/32/6982_2.png) [@guilhermebodin](https://discourse.julialang.org/u/guilhermebodin)\
**Post date:** [July 28, 2019, 1:41am UTC](https://discourse.julialang.org/t/filling-a-preallocated-array-without-allocations/26896/1 "2019-07-28T01:41:03Z")

</div>

Hello, does anybody know if it is possible to fill a preallocated array without allocations?

In other words, is there a way of performing this function `loop` without allocations

```julia
mutable struct KF
    F::Array{Float64, 3}
    function KF()
        new(rand(2, 2, 100))
    end
end

function loop(kfaux::KF)
    @inbounds for t in 40:100
        kfaux.F[:, :, t] = kfaux.F[:, :, t-1]
    end
    return
end

kfaux = KF()
using BenchmarkTools
@benchmark loop($kfaux)

```

I got

```julia
julia> @benchmark loop($kfaux)
BenchmarkTools.Trial: 
  memory estimate: 6.67 KiB
  allocs estimate: 61
  --------------
  minimum time: 3.361 μs (0.00% GC)
  median time: 3.467 μs (0.00% GC)
  mean time: 4.745 μs (15.47% GC)
  maximum time: 860.028 μs (98.64% GC)
  --------------
  samples: 10000
  evals/sample: 8

```

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [July 28, 2019, 4:59am UTC](https://discourse.julialang.org/t/filling-a-preallocated-array-without-allocations/26896/2 "2019-07-28T04:59:55Z")

</div>

Sure–one way to do it is just to write out the loop:

```julia
julia> function loop(kfaux::KF)
           for t in 40:100
               for j in axes(kfaux.F, 2)
                 for i in axes(kfaux.F, 1)
                   kfaux.F[i, j, j] = kfaux.F[i, j, t - 1]
                 end
               end
           end
       end
loop (generic function with 1 method)

julia> @btime loop($kfaux)
  496.222 ns (0 allocations: 0 bytes)

```

---

<div class="post-metadata">

**Author:** ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)\
**Post date:** [July 28, 2019, 1:53pm UTC](https://discourse.julialang.org/t/filling-a-preallocated-array-without-allocations/26896/3 "2019-07-28T13:53:44Z")

</div>

In addition, if the dimensions of your example is representative of what you are really trying to do, maybe it makes sense to swap `Array{T, 3}` to `Vector{SMatrix}` using StaticArrays

```julia
using StaticArrays

mutable struct KFS
    F::Vector{SMatrix{2,2,Float64,4}}
    function KFS()
        new([@SMatrix rand(2,2) for _ in 1:100])
    end
end

function loop(kfaux::KFS)
    F = kfaux.F
    @inbounds for t in 40:100
        F[t] = F[t-1]
    end
    return
end

```

Benchmarks:

```julia
julia> using BenchmarkTools

julia> @btime loop($kfaux) # Original version
  2.503 μs (61 allocations: 6.67 KiB)

julia> @btime loop′($kfaux) # Robin's version
  459.447 ns (0 allocations: 0 bytes)

julia> @btime loop($kfauxs)
  18.602 ns (0 allocations: 0 bytes)

```

---

<div class="post-metadata">

**Author:** ![Ahmed\_Salih](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ahmed_salih/32/206579_2.png) [@Ahmed\_Salih](https://discourse.julialang.org/u/Ahmed_Salih)\
**Post date:** [July 28, 2019, 4:46pm UTC](https://discourse.julialang.org/t/filling-a-preallocated-array-without-allocations/26896/4 "2019-07-28T16:46:48Z")

</div>

Can you explain why this is allocation less? Would like to learn 🙂

Kind regards

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [July 28, 2019, 8:02pm UTC](https://discourse.julialang.org/t/filling-a-preallocated-array-without-allocations/26896/5 "2019-07-28T20:02:32Z")

</div>

Sure! 🙂

When you write `x[:, :, t]`, you are making a _copy_ of that slice of the array, so this line:

```julia
x[:, :, t] = x[:, :, t - 1]

```

makes a copy of `x[:, :, t - 1]` and then assigns that to `x[:, :, t]`.

You can use a view instead:

```julia
x[:, :, t] .= @view x[:, :, t - 1]

```

but it does not make a huge difference in your particular case because the sizes of the first two dimensions of your array are so small.

A loop doesn’t require creating a copy or a view at all, so it’s a nice solution. I would also second @fredrikekre’s suggestion: if your data structure is actually a collection of N 2x2 matrices, then it’s much nicer to work with it in that way, and using StaticArrays makes that very efficient.

---

<div class="post-metadata">

**Author:** ![Ahmed\_Salih](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ahmed_salih/32/206579_2.png) [@Ahmed\_Salih](https://discourse.julialang.org/u/Ahmed_Salih)\
**Post date:** [July 28, 2019, 8:23pm UTC](https://discourse.julialang.org/t/filling-a-preallocated-array-without-allocations/26896/6 "2019-07-28T20:23:30Z")

</div>

Thanks, so loops are actually pretty smart, nice to know. Used to that vectorizing would be faster, so that is why I sometimes have a hard time grasping these kind of things, but I really liked your explanation.

Kind regards

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [July 28, 2019, 8:32pm UTC](https://discourse.julialang.org/t/filling-a-preallocated-array-without-allocations/26896/7 "2019-07-28T20:32:54Z")

</div>

“Vectorizing” in that sense is only necessary in languages where loops are slow (matlab, python, etc.). After all, a vectorized operation in numpy or matlab is actually implemented via a loop in a fast language (like C). Julia is a fast language, so you can choose a vectorized operation or a loop based on whichever one makes your particular task easier to write, read, or understand.

---

<div class="post-metadata">

**Author:** ![guilhermebodin](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/guilhermebodin/32/6982_2.png) [@guilhermebodin](https://discourse.julialang.org/u/guilhermebodin)\
**Post date:** [July 29, 2019, 6:05pm UTC](https://discourse.julialang.org/t/filling-a-preallocated-array-without-allocations/26896/8 "2019-07-29T18:05:28Z")

</div>

Thanks! It helped a lot! 🙂
