Vectors with elements of same type but different parametric type

I see a large improvement if I convert your type to isbits. Note that you do not need to store the type as a field for your struct, since it’s already stored in the type itself. Additionally, if xy is guaranteed to be just 2 Float64 in size, then a vector is a poor choice, and I think an SVector from StaticArrays package would be better to avoid the tiny heap allocation In this example I just use a tuple:

struct PointWithLabel{L<:AbstractLabel}
    xy::Tuple{Float64, Float64}
end

function getlabel(::PointWithLabel{L}) where L
    return L
end

Then benchmarking as before:

@btime foreach(getlabel, pointAs);
# 10.590 ns (0 allocations: 0 bytes)

@btime foreach(getlabel, pointABCs);
# 28.406 ms (0 allocations: 0 bytes)

@btime foreach(getlabel, unionPoints)
# 14.096 μs (0 allocations: 0 bytes)

In the case of the first and third benchmarks, we are accessing values stored directly inline to the array. And so these are much faster than before. Clearly, however, since the 3rd example is still 1000x slower than the first, there’s a lot of overhead involved with resolution of types in unions. Meanwhile, the middle example is stored as an array of pointers, and that pointer indirection is clearly very expensive.

1 Like