I want this code to run as fast as possible. And what is the most efficient way to iterate over a list of objects and change their fields or calculate some variables using them?
Here is my code:
mutable struct typeA
a::Float64
end
mutable struct typeB
b::Float64
end
mutable struct typeC
c::Float64
end
types = Union{typeA, typeB, typeC}
function change(n::Int64, list::Array{types, 1})
for i = 1:n
j = rand(1:3)
chosen = list[j]
u = rand()
if typeof(chosen) == typeA
if u < chosen.a
chosen.a = u
end
elseif typeof(chosen) == typeB
if u < chosen.b
chosen.b = u
end
elseif typeof(chosen) == typeC
if u > chosen.c
chosen.c = u
end
end
end
list
end
list = Union{types}[typeA(0.7), typeB(0.5), typeC(0.9)]
@time change(10000, list)
And here is the results:
0.072776 seconds (85.81 k allocations: 4.694 MiB)
And for the second time:
0.001378 seconds (4 allocations: 160 bytes)