Allocation depending on value of typed field in struct

I’m seeing some behavior with accessing data members of structs that I don’t understand - depending on the value of typed field in a struct, I’m getting an allocation with getfield.

struct MyStruct
   v::Int
end


ms0 = MyStruct(0)
ms512 = MyStruct(512)

@btime getfield(ms0, :v)
  15.415 ns (0 allocations: 0 bytes)

@btime getfield(ms512, :v)
  20.361 ns (1 allocation: 16 bytes)

It seems that for values less than 512, there is no allocation. I also do not see any allocations for any size number if I instead define the field v without a type. Is there a reason for this?

Also, why does accessing the member directly with . cause more allocations and why is it so much slower?

@btime ms0.v
  43.088 ns (1 allocation: 16 bytes)

@btime ms512.v
  51.874 ns (3 allocations: 48 bytes)

You’re using non constant global variable

3 Likes

Try

These should both be expected to use zero time.

1 Like

Interesting:

  1. Making them const is basically free (0.001 ns and no allocations).
  2. Putting the creation and getfield into a function also made it free
  3. Trying @DNF’s suggestion, resulted in a time of 1.100 ns with 0 allocations

I’m assuming (1) and (2) are due to the whole thing being compiled out and essentially returning the value? How/why does (3) behave differently than these?

It’s probably just benchmarking artefacts. It’s difficult to get good, accurate timings of operations that are essentially free. In statically inferred code this should not take any time at all.

1 Like