Type Intersection in Arrays

Anyhow this is going off topic, but I’ll be happy to discuss this elsewhere

This is actually nice when I know that there is only one type. I’d need to check whether there is any performance gain though.

Why not [x...] ?

By all means avoid splatting a collection with arbitrary length, unless you really know it can only have a few elements.

But he already said he doesn’t care about speed…

I guess the splatting is maybe the idea that most explicitly captures that I want the type intersection.

how bad would the performance penalty be for - say - 1000 elements?

On 0.7-beta it’s actually faster:

julia> x = Vector{Any}(randn(100_000)); @time [x...];
  0.001294 seconds (7 allocations: 1.526 MiB)

julia> @time identity.(x);
  0.004294 seconds (199.50 k allocations: 3.807 MiB)

EDIT: before someone complains about using @time:

julia> foo(x) = [x...]; @btime foo(x)
  427.769 μs (3 allocations: 1.53 MiB)

julia> @btime identity.(x);
  3.698 ms (199497 allocations: 3.81 MiB)
1 Like

The question isn’t really how fast it is for 100 entries, it’s more whether the number of entries can vary, in which case a new method will be compiled for each new number of entries. So you need to include the compilation time too, plus the memory cost of having these compiled methods in the cache.

Good point. Likely there is no serious penalty how I use this at the moment, but good to be aware.

How would you solve this problem?

I guess we need a function like this:

function promote_entries(A::AbstractArray)
    T = mapreduce(typeof, promote_type, A)
    convert(Array{T}, A)
end

Currently this doesn’t seem to be optimized when A is homogeneous, which is a bit annoying but could easily be fixed by handling that situation manually.

1 Like