Structs: mutable versus immutable

I just tried on some small part of different code and you are right. It was probably benchmark artifact.

Beware: both codes do absolutely nothing to the contents of the array.

Must be:

function change_vec1!(vec)
    for i in eachindex(vec)
        s = vec[i]
        vec[i] = TestStruct(2*s.a,s.b)
    end
end

function change_vec2!(vec)
    for i in eachindex(vec)
        s = vec[i]
        vec[i] = @set s.a = 2*s.a
    end
end

x inside for x in itr is a value of item, not a reference to it. Re-binding x inside the loop body does not change the value in itr. E.g.

julia> v = collect(1:5)
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> for x in v
           x += 5
           println(x)
       end
6
7
8
9
10

julia> v
5-element Array{Int64,1}:
 1
 2
 3
 4
 5
2 Likes

Yes… my bad. Then the benchmark above is wrong. Mutating the field of the mutable struct is faster than copying the immutable structs even if the array contained in the structure is small and static. Probably one can see a great performance benefit if all fields are immutable and we are mutating all of them (actually the threshold is well known, and the size up to which StaticArrays are recommended, ~10).

1 Like