logo

Comparison of the Speed of the Equality Operator == for Characters and Integers in Julia 📂Julia

Comparison of the Speed of the Equality Operator == for Characters and Integers in Julia

Conclusion

Comparing each element in an array using the Equal Operator == shows that Char is faster than integers.

Speed Comparison

julia> integer = rand(1:5, N); print(typeof(integer))
Array{Int64,1}
julia> character = rand(['S','E','I','R','D'], N); print(typeof(character))
Array{Char,1}
julia> @time integer .== 1;
  0.009222 seconds (6 allocations: 1.196 MiB)

julia> @time character .== 'S';
  0.005266 seconds (7 allocations: 1.196 MiB)

The above code identifies where 1 and S are located in an array made of integers and characters, respectively. Except for the difference between being an integer or a character, everything else is exactly the same, yet there’s a significant difference in time consumption, almost double. Therefore, using characters is recommended in the code optimization process as it’s a commonly used method.

Further Research

julia> string = rand(["S","E","I","R","D"], N); print(typeof(string))
Array{String,1}
julia> @time string .== "S";
  0.072692 seconds (7 allocations: 1.196 MiB)

As one would expect, using a String instead of a Character causes more than a tenfold increase in speed degradation.

Environment

  • OS: Windows
  • julia: v1.5.0