Mutable structs with all constant fields outperform immutable structs for equality comparison

You didn’t define == for the new types, though. The default == method just forwards to ===:

julia> struct S end

julia> @which S() == S()
==(x, y)
     @ Base Base.jl:207

So it comes down to === being cheaper for the mutable struct, because it’s implemented as a simple integer comparison, unlike for the immutable struct, where the === is recursive. This is documented, the doc string of === starts with:

Determine whether x and y are identical, in the sense that no program could distinguish them. First the types of x and y are compared. If those are identical, mutable objects are compared by address in memory and immutable objects (such as numbers) are compared by contents at the bit level.

Regarding the unfortunate default method of ==, here are some Github issues:

The behavior is documented, though, the == doc string starts with:

Generic equality operator. Falls back to ===.

9 Likes