# Type stability with variable arguments

**URL:** <https://discourse.julialang.org/t/type-stability-with-variable-arguments/74640>\
**Category:** Performance\
**Tags:** type-stability\
**Created:** [January 14, 2022, 7:22pm UTC](https://discourse.julialang.org/t/type-stability-with-variable-arguments/74640 "2022-01-14T19:22:44Z")\
**Posts on this page:** 1\
**Showing post:** 9

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [January 15, 2022, 2:08pm UTC](https://discourse.julialang.org/t/type-stability-with-variable-arguments/74640/9 "2022-01-15T14:08:51Z")

</div>

> [@atteson](#):
>
> One of them is sort on multiple large vectors using lexicographic ordering as illustrated below.

Ordering for tuples is already lexicographic as noted by @tomerarnon, so you can just map into a tuple:

```julia
lexicographic(x...) = i -> getindex.(x, i)

```

and `sort(..., by=lexicographic(args...))`.

In general, it is instructive to see how Base implements functions acting on variable-length arguments or variable-length tuples in a type-stable way. The key thing is that, because the compiler knows the length of a tuple, if you write things in the correct way then it can completely unroll loops as if you had written it out by hand.

For example, here is how `isless` is implemented for tuples: [base/tuple.jl:isless](https://github.com/JuliaLang/julia/blob/7ab26e0c85d53e47c3c1127650703bdfb9c6ada8/base/tuple.jl#L470-L482). Note that it is recursive, but the compiler can “unroll” the recursion completely (if it is not too deep). `map` is [implemented similarly](https://github.com/JuliaLang/julia/blob/7ab26e0c85d53e47c3c1127650703bdfb9c6ada8/base/tuple.jl#L219-L224), and also broadcasting on tuples as exploited above in the `getindex.(...)` call. Another useful pattern is to use the `ntuple` function with a `Val{N}` argument where `N` comes from a type parameter (e.g. a [`Vararg` parameter](https://docs.julialang.org/en/v1/base/base/#Core.Vararg) for variable arguments), in which case the compiler can completely unroll the loop; a simple example of this can be found in the [`size(a::Array)` function](https://github.com/JuliaLang/julia/blob/7ab26e0c85d53e47c3c1127650703bdfb9c6ada8/base/array.jl#L153) and much more extensive use can be found in the [multidimensional `reverse!` implementation](https://github.com/JuliaLang/julia/blob/7ab26e0c85d53e47c3c1127650703bdfb9c6ada8/base/arraymath.jl#L74-L98).

---

_[View the full topic](https://discourse.julialang.org/t/type-stability-with-variable-arguments/74640)._
