# Understanding allocations

Hi,

I have troubles understanding why `foo` allocates whereas `foo` does not:

`````` 1.623 ms (65804 allocations: 1.18 MiB)
7.578 μs (0 allocations: 0 bytes)
``````

Does someone know why?

Thank you,

``````using Parameters, BenchmarkTools

@with_kw mutable struct Mesh
V = randn(100,110)
end

function foo1(V,g)
Nw,Nv = size(V)
for j=1:Nw
for i=1:Nv
gij  = g[j,i]
gimj = (i > 1 )        ? g[j,i-1] : zero(gij)

Fij  = (i > 1)         ? ((V[j,i]>=0.)   ? V[j,i]   * gimj : V[j,i]   * gij)  : zero(gij)

end
end
end

function foo(m,g)
Nw,Nv = size(m.V)
for j=1:Nw
for i=1:Nv
gij  = g[j,i]
gimj = (i > 1 )        ? g[j,i-1] : zero(gij)

Fij  = (i > 1)         ? ((m.V[j,i]>=0.)   ? m.V[j,i]   * gimj : m.V[j,i]   * gij)  : zero(gij)
end
end
end

V0 = rand(100,110)
g1 = randn(100,110)

m = Mesh()
@btime foo(\$m,\$g1)
@btime foo1(\$(m.V),\$g1)
``````

Your Mesh isn’t strictly typed. Do:

``````@with_kw mutable struct Mesh
V::Matrix{Float64} = randn(100,110)
end
``````
1 Like

Well… thank you!