Performance of collections with Functions as abstract type

Benchmarking in a local scope shows:

julia> function test(v, x)
           y = similar(x)
           for ii in eachindex(v)
               y[ii] = v[ii](x[ii])
           end
           y
       end;

julia> using BenchmarkTools

julia> @btime test($vsin, $x);
  1.561 ms (2 allocations: 781.30 KiB)

julia> @btime test($vf, $x);
  6.122 ms (299491 allocations: 5.33 MiB)

Interestingly, if it’s known to be a small union of functions, one may use

julia> v2 = convert(Vector{Union{typeof(sin),typeof(cos)}}, vf);

julia> @btime test($v2, $x);
  1.621 ms (2 allocations: 781.30 KiB)

Perhaps there should be some heuristic to use a union as the eltype if there are only a few functions, instead of using the supertype.

2 Likes