Why is converting from a type to a symbol so slow?

Symbol(x) for generic x falls back to printing x to a string, then converting the string to a symbol. This is going to be slow (allocating a new string on each call, among other things).

If you just want an arbitrary ordering, you can compare by the objectid of the type. For example:

julia> sort(Any[3, 4.2, 6, 5.6, "x", 7, "y"], by=objectid∘typeof)
7-element Vector{Any}:
 3
 6
 7
 4.2
 5.6
  "x"
  "y"

Of course, if you have a mixed-type container, such as an array holding elements of different types, you are inherently looking at sub-par Julia performance to start with.

4 Likes