3 different ways to create an array have different performance

I am creating an array of size 100 using three different methods. But I don’t understand why the @time results are different between them.

Here is the code

Main> @time dpc = [Int(round(rand(PP_DD))) for i=1:100];
  0.033401 seconds (9.36 k allocations: 511.468 KiB)

Main> @time dpc = Int.(round.(rand(PP_DD, 100)));
  0.020636 seconds (4.13 k allocations: 235.887 KiB)

Main> @time begin
       dpc = zeros(Int64, 100)
       for i = 1:100
           dpc[i]=Int(round(rand(PP_DD)))
       end
       end
  0.000056 seconds (201 allocations: 4.000 KiB)

where PP_DD = Normal(4.5, 1)

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