logo

The Difference Between == and === in Julia 📂Julia

The Difference Between == and === in Julia

Code 1

== compares whether values are the same, and === operates differently depending on whether the values to be compared are Mutable or not.

  • Mutable: Checks if both terms refer to the same object, in other words, it returns whether the two variables can be programmatically distinguished or not.
  • Immutable:
    • Checks if both terms are of the same type,
    • Checks if both terms have the same structure,
    • And recursively checks if each element is == the same.
julia> X = 1; Y = 1;

julia> X == Y
true

julia> X === Y
true

julia> X = [1]; Y = [1];

julia> X == Y
true

julia> X === Y
false

For example, looking at the above execution result commonly seen in Python, the integer 1 is Immutable and programmatically indistinguishable, so both == and === return true. However, when looking at an array containing only 1, if a new element is added to X, X and Y can become different because they are Mutable, so == returns true for simply comparing values, while === returns false for comparing the objects themselves.

You can understand enough just by grasping this usage even if you don’t really know what objects mean.

Optimization

In Julia, which has weak object orientation, such differences are not significantly impactful. From the perspective of code optimization, the comparison of == and === shows the following level of performance difference in the comparison of Singletons.

N = 10^7
x = rand(0:9, N)

julia> @time for t ∈ 1:N
           x[t] == 0
       end
  1.292501 seconds (30.00 M allocations: 610.336 MiB, 2.63% gc time)

julia> @time for t ∈ 1:N
           x[t] === 0
       end
  1.016211 seconds (30.00 M allocations: 610.336 MiB, 2.77% gc time)

A value is usually Immutable, so it’s understood that === is faster than ==.

Such differences might not be significant in most cases. Needless to say, non-Iterative tasks are much faster, like the following vector operations, where speed differences are negligible or none.

julia> @time x .== 0;
  0.009509 seconds (6 allocations: 1.196 MiB)

julia> @time x .=== 0;
  0.009478 seconds (6 allocations: 1.196 MiB)

Environment

  • OS: Windows
  • julia: v1.6.1