Vectors vs. Tuples and multiple dispatch

Use StaticArrays.jl instead of tuples. Then you can use your original f definition and it will be fast (by avoiding heap allocations and unrolling loops):

julia> using BenchmarkTools, StaticArrays

julia> F(x, a) = 1.2*exp(-a*x)
F (generic function with 1 method)

julia> f(x,a) = vcat(1, F.(cumsum(x),a))
f (generic function with 1 method)

julia> x = @SVector[0.1, 0.2]
2-element SVector{2, Float64} with indices SOneTo(2):
 0.1
 0.2

julia> @btime f($x, 0.5)
  0.051 ns (0 allocations: 0 bytes)
3-element SVector{3, Float64} with indices SOneTo(3):
 1.0
 1.1414753094008567
 1.0328495717100694

In general, StaticArrays are a good idea when you have small (≲ 10 element) arrays whose size is more-or-less fixed (typically it should be inferred at compile-time from the function inputs).

8 Likes