I'm wondering about immutable types and performances in Julia.
In which case does making a composite type immutable improve perfomances? The documentation says
They are more efficient in some cases. Types like the Complex example above can be packed efficiently into arrays, and in some cases the compiler is able to avoid allocating immutable objects entirely.
I don't really understand the second part.
Are there cases where making a composite type immutable reduce performance (beyond the case where a field needs to be changed by reference)? I thought one example could be when an object of an immutable type is used repeatedly as an argument, since
An object with an immutable type is passed around (both in assignment statements and in function calls) by copying, whereas a mutable type is passed around by reference.
However, I can't find any difference in a simple example:
abstract MyType type MyType1 <: MyType v::Vector{Int} end immutable MyType2 <: MyType v::Vector{Int} end g(x::MyType) = sum(x.v) function f(x::MyType) a = zero(Int) for i in 1:10_000 a += g(x) end return a end x = fill(one(Int), 10_000) x1 = MyType1(x) @time f(x1) # elapsed time: 0.030698826 seconds (96 bytes allocated) x2 = MyType2(x) @time f(x2) # elapsed time: 0.031835494 seconds (96 bytes allocated)
So why isn't
f
slower with an immutable type? Are there cases where using immutable types makes a code slower?
x = MyType2([1:4]); x.v[1] = 5
. This operation is in-place so it doesn't change the reference. So in both type cases the vector in v should be passed by reference. – mmagnuski