Efficiently looping over structs in Julia

If you want the struct to be mutable, why not reuse it in each loop?

using Distributions, BenchmarkTools

mutable struct help_me{Z}
    can_you_help_me::Z
    millions_of_thanks::Z
end

function set_help!(h, x, y)
    h.can_you_help_me = x;
    h.millions_of_thanks = y;
end

function runner()
    tmp_help = help_me(rand(Bernoulli(0.5)), rand(Bernoulli(0.99)));
    max_iter = 10_000;
    for i in 1:max_iter
        set_help!(tmp_help, rand(Bernoulli(0.5)), rand(Bernoulli(0.99)));
        # many follow-up processes 
    end
end

@btime runner()
  116.107 μs (0 allocations: 0 bytes)
5 Likes