Thanks all for your suggestions. I am avoiding the use of packages (I want to run it on my mobile phone). I did some testing with three approaches using rand() and fill() thinking that it might be quicker not to generate random numbers. Interesting results:
- Mutable struct (consistently faster to initialise with rand rather than fill):
julia> @time begin
mutable struct Foo
A
B
C
end
k = 30
X = [Foo(rand(2,2), rand(1,2), rand(3,2)) for _ in 1:k]
X[1].A = rand(3,2)
X[1].B = rand(2,2)
X[1].A *X[1].B
end
0.033101 seconds (66.55 k allocations: 3.532 MiB)
3×2 Array{Float64,2}:
0.526554 0.52724
0.0632389 0.159635
0.0985826 0.862068
julia> @time begin
mutable struct Foo
A
B
C
end
k = 30
X = [Foo(fill(2,2), fill(1,2), fill(3,2)) for _ in 1:k]
X[1].A = rand(3,2)
X[1].B = rand(2,2)
X[1].A *X[1].B
end
0.044417 seconds (76.86 k allocations: 3.938 MiB)
3×2 Array{Float64,2}:
0.427698 0.169891
0.177593 0.0979178
0.407794 0.303872
- Dict approach. Note I couldn’t initialise with fill(), so had to use rand(). This approach was the slowest by far:
julia> @time begin
k = 30
keys = [:a,:b,:c]
x = [Dict(key=>fill(0.0,1,1) for key in keys) for _ in 1:k]
for i = 1:k
x[k][:a] = rand(2,2)
x[k][:b] = rand(1,2)
x[k][:c] = rand(3,2)
end
x[1][:a]= rand(3,2)
x[1][:b]= rand(2,2)
x[1][:a]*x[1][:b]
end
0.095423 seconds (188.87 k allocations: 9.871 MiB)
3×2 Array{Float64,2}:
0.922558 0.830295
0.963615 0.82152
0.765743 0.685305
- undefined array approach (fastest outcome):
julia> @time begin
k=30
A = Array{Any}(undef, k)
B = Array{Any}(undef, k)
C = Array{Any}(undef, k)
for i = 1:k
A[i] = rand(2,2)
B[i] = rand(1,2)
C[i] = rand(3,2)
end
A[1]= rand(3,2)
B[1]= rand(2,2)
A[1]*B[1]
end
0.000037 seconds (127 allocations: 12.156 KiB)
3×2 Array{Float64,2}:
0.445011 0.346964
0.821819 0.64577
0.476496 0.376766
julia> @time begin
julia> @time begin
k=30
A = Array{Any}(undef, k)
B = Array{Any}(undef, k)
C = Array{Any}(undef, k)
for i = 1:k
A[i] = fill(2,2)
B[i] = fill(1,2)
C[i] = fill(3,2)
end
A[1]= rand(3,2)
B[1]= rand(2,2)
A[1]*B[1]
end
0.000031 seconds (127 allocations: 10.750 KiB)
3×2 Array{Float64,2}:
1.33985 0.496884
0.549631 0.0953787
1.33206 0.450659
Thanks all for your suggestions, I learned lots from you all!