I found that @code_warntype indicated a type instability in a finite difference code. The same issue arises in the following simple example.
using OffsetArrays
abstract type AbstractGrid end
struct Grid <: AbstractGrid
x::Vector{Float64}
end
function Grid(L, N)
x = range(0, L, N+1)
return Grid(x)
end
struct OGrid <: AbstractGrid
x::OffsetVector{Float64}
end
function OGrid(L, N)
x_ = range(0, L, N+1)
x = OffsetVector(x_, 0:N)
return OGrid(x)
end
function average(f::Function, grid::AbstractGrid)
x = grid.x
s = 0.0
for k in eachindex(x)
s+= f(x[k])
end
return s / length(x)
end
I don’t know how well your MWE approximates your actual use case, but I would just point out that by forcing Grid and OGrid to use Vector{Float64} you are converting ranges to fully allocated arrays, which seems a bit wasteful, given that Julia provides the very nice, lightweight range datatypes.
Unless you mostly use non-uniformly spaced grids, isn’t it better to use ranges?