The cost that a type instability incurs is a dynamic dispatch upon each subsequent function call within that function body. If there’s only one or two dynamic dispatches, then it’s not a big deal, but if you go on to use the unstable variable within a hot for loop or somesuch, then it’s a problem.
The easiest way to limit this cost is by using a function barrier. This is a simple approach that just moves everything below the instability into an inner function. Julia will pay the dynamic dispatch cost once — to get into the inner function — but once you’re inside that inner function everything will be specialized and stable.
Alternatively, if you’re taking your slices inside that hot loop, you can use a Val
to hoist the dimension into the type domain, which then demands specialization for that particular value:
outer(d) = inner(Val(d))
function inner(::Val{dim}) where dim
for i in blah
slice = selectdim(A, dim, i)
…