3 different ways to create an array have different performance

Don’t benchmark in global scope:

julia> const PP_DD = Normal(4.5, 1)
Distributions.Normal{Float64}(μ=4.5, σ=1.0)

julia> f1() = [Int(round(rand(PP_DD))) for i=1:100]
f1 (generic function with 1 method)

julia> f2() = Int.(round.(rand(PP_DD, 100)));

julia> f3() = begin
         dpc = zeros(Int64, 100)
         for i = 1:100
           dpc[i]=Int(round(rand(PP_DD)))
         end
       end
f3 (generic function with 1 method)

julia> @btime f1();
  1.836 μs (1 allocation: 896 bytes)

julia> @btime f2();
  1.647 μs (2 allocations: 1.75 KiB)

julia> @btime f3();
  1.890 μs (1 allocation: 896 bytes)
9 Likes