Efficiently looping over structs in Julia

Hello,

I have a dire question with regards to memory allocation of structs. I have posted it in Stackoverflow; please answer it in Stackoverflow:

https://stackoverflow.com/q/65403410/14869451

Many thanks.

There are already helpful answers by @Oscar_Smith posted in SO.

2 Likes

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

Thanks a lot!

Just for if it was not clear from the answer in the Stack Overflow, the allocations were not associated to the loop initializing the struct. This is fast and does not allocate either:

struct help_me2{Z}
    can_you_help_me::Z
    millions_of_thanks::Z
end

function runner2()
    tmp_help = help_me2(rand(Bernoulli(0.5)), rand(Bernoulli(0.99)));
    max_iter = 10_000;
    for i in 1:max_iter
        tmp_help = help_me2(rand(Bernoulli(0.5)), rand(Bernoulli(0.99)))
        # many follow-up processes 
    end
end
@btime runner2()

Indeed, it is likely that this will be faster than the option using the mutable struct. But if you want a mutable struct or not depends on what you want to do with it afterwards.