Interpolations.jl interpolation evaluation causes allocation

In the following MWE, all interpolation evaluations cause 1 allocation. I want to get rid of this allocation for optimal performance. What should I do to achieve this?

using Interpolations, BenchmarkTools

# Create test data
n = 5  # Size of test matrix
alphas = range(-10, 10, n)  # Angle of attack range: -10° to 10°
d_trailing_edge_angles = range(0, 30, n)  # Trailing edge deflection: 0° to 30°

# Create cl_matrix with a simple aerodynamic model
cl_matrix = zeros(n, n)
for (i, alpha) in enumerate(alphas)
    for (j, delta) in enumerate(d_trailing_edge_angles)
        # Simple linear combination of angle of attack and trailing edge deflection
        cl_matrix[i,j] = 2π * (deg2rad(alpha) + 0.3 * deg2rad(delta))
    end
end

cl_interp = extrapolate(scale(interpolate(cl_matrix, BSpline(Linear())), alphas, d_trailing_edge_angles), NaN)
@btime cl_interp[0.0, 0.0]
cl_interp = scale(interpolate(cl_matrix, BSpline(Linear())), alphas, d_trailing_edge_angles)
@btime cl_interp[0.0, 0.0]
cl_interp = interpolate((alphas, d_trailing_edge_angles), cl_matrix, Gridded(Linear()))
@btime cl_interp[0.0, 0.0]

Output:

  62.233 ns (1 allocation: 16 bytes)
  61.350 ns (1 allocation: 16 bytes)
  84.053 ns (1 allocation: 16 bytes)

Use GitHub - JuliaMath/Dierckx.jl: Julia package for 1-d and 2-d splines instead?

Try

@btime $cl_interp[0.0, 0.0]

You’re benchmarking a kernel with a non-const and Any-typed global variable cl_interp, causing a small allocation. Usually you’d pass it to an argument whose type could be inferred. BenchmarkTools does this with $-interpolation:

julia> @btime cl_interp[0.0, 0.0]
  84.511 ns (1 allocation: 16 bytes)
0.0

julia> @btime $cl_interp[0.0, 0.0]
  64.658 ns (0 allocations: 0 bytes)
0.0

Additionally, the indexing syntax is deprecated, you could see the warnings in a --depwarn=yes session, but the method’s file is also a hint:

julia> @which cl_interp[0.0, 0.0]
getindex(itp::AbstractInterpolation{T, N}, i::Vararg{Number, N}) where {T, N}
     @ Interpolations deprecated.jl:103

The replacement is just cl_interp(0.0, 0.0).

2 Likes