Struct and memory allocation

Hello ! :slight_smile:
I don’t understand why there is memory allocation when I acces to a parameters of my immutable struct ?

julia> using BenchmarkTools
julia> struct S1
       a::NTuple{3,Int64}
       b::Float64
       end

julia> s = S1((1,2,3), 4.5)
S1((1, 2, 3), 4.5)

julia> @btime s.a
  31.791 ns (2 allocations: 80 bytes)
(1, 2, 3)

julia> @allocated s.a
80

I read the post Mutability · JuliaNotes.jl (m3g.github.io) and Common allocation mistakes - General Usage / Performance - Julia Programming Language (julialang.org) but I don’t understand this case.

Thanks !
fdekerm

You are working in global scope. Put your code in a function and try again.

1 Like

Thanks you are right, I am wrong to do my tests in the REPL

julia> function f(s)
       s.a
       end
f (generic function with 2 methods)

julia> @btime f(s)
  14.228 ns (1 allocation: 32 bytes)
(1, 2, 3)

But always 1 allocation ?

As described in the docs, you need to interpolate s with the $ symbol whenever benchmarking something with either @btime or @benchmark

In [1]: @btime $s.a
  2.500 ns (0 allocations: 0 bytes)
(1, 2, 3)

In [2]: @btime f($s)
  2.700 ns (0 allocations: 0 bytes)
(1, 2, 3)
1 Like

Thanks ! :+1: I didn’t read the documentation carefully!
So there is no difference in terms of performance/allocation between 1) and 2):

julia> function g(t)
       t[1]
       end
g (generic function with 1 method)

1)

julia> g(s.a)
1

2)

julia> t = s.a
(1, 2, 3)

julia> g(t)
1
1 Like