# Why selectdim is type instable

**URL:** <https://discourse.julialang.org/t/why-selectdim-is-type-instable/25271>\
**Category:** General Usage\
**Tags:** question\
**Created:** [June 13, 2019, 8:27pm UTC](https://discourse.julialang.org/t/why-selectdim-is-type-instable/25271 "2019-06-13T20:27:14Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![mbauman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mbauman/32/31082_2.png) [@mbauman](https://discourse.julialang.org/u/mbauman)\
**Post date:** [August 13, 2019, 8:51pm UTC](https://discourse.julialang.org/t/why-selectdim-is-type-instable/25271/5 "2019-08-13T20:51:44Z")

</div>

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:

```julia
outer(d) = inner(Val(d))
function inner(::Val{dim}) where dim
    for i in blah
         slice = selectdim(A, dim, i)
    …

```

---

_[View the full topic](https://discourse.julialang.org/t/why-selectdim-is-type-instable/25271)._
