Search code examples
randomjuliaallocationmutate

Mutate existing container for `rand` results in Julia?


I have a simulation where the computation will reuse the random sample of a multi-dimensional random variable. I'd like to be able to re-use a pre-allocated container for better performance with less allocations.

Simplified example:

function f()
    container = zeros(2) # my actual use-case is an MvNormal
    map(1:100) do i
        container = rand(2)
        sum(container)
    end
end

I think the above is allocating a new vector as a result of rand(2) each time. I'd like to mutate container by storing the results of the rand call.

I tried the typical pattern of rand!(container,...) but there does not seem to be a built-in rand! function following the usual mutation convention in Julia.

How can I reuse the container or otherwise improve the performance of this approach?


Solution

  • rand! exists in the Random module

    julia> using Random
    
    julia> a = zeros(2)
    2-element Vector{Float64}:
     0.0
     0.0
    
    julia> rand!(a);@show a;
    a = [0.8139794738918935, 0.6336948436048475]