# Dispatching by values is very slow - Feature or Problem?

**URL:** <https://discourse.julialang.org/t/dispatching-by-values-is-very-slow-feature-or-problem/65586>\
**Category:** Performance\
**Tags:** dispatch\
**Created:** [July 31, 2021, 8:33am UTC](https://discourse.julialang.org/t/dispatching-by-values-is-very-slow-feature-or-problem/65586 "2021-07-31T08:33:27Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![viraltux](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/viraltux/32/15236_2.png) [@viraltux](https://discourse.julialang.org/u/viraltux)\
**Post date:** [July 31, 2021, 11:10am UTC](https://discourse.julialang.org/t/dispatching-by-values-is-very-slow-feature-or-problem/65586/3 "2021-07-31T11:10:10Z")

</div>

> [@Sukera](#):
>
> `@benchmark` already loops for you and you’re also counting creation time of the random matrix, so that’s going to skew your benchmark significantly. I recommend using the `setup` keyword for `@benchmark` (e.g. `setup=(x=rand(n))` and passing `x` to `sort!` without interpolation), as well as `evals=1` to make sure each matrix is only ever used once.

`BenchmarkTools` is not very well suited to compare benchmarks as discussed in [Identical functions benchmark differently](https://discourse.julialang.org/t/identical-functions-benchmark-differently/65345) but that’s another story. Actually benchmarks with those settings only makes differences wider, and using a dispatching function instead dispatching by value makes `sortn!` **~300% faster** than default `Base.sort!`

```julia
using SortingNetworks
n = 4

#206.279 μs ± 10.895 μs
@benchmark for i in 1:10000 sort!(x) end setup=(x=rand(n)) evals=1

#64.406 μs ± 5.169 μs
@benchmark for i in 1:10000 sortn!(x) end setup=(x=rand(n)) evals=1

```

and for `sort` vs `swapsort`

```julia
# 565.565 μs ± 142.188 μs
@benchmark for i in 1:10000 sort(x) end setup=(x=rand(n)) evals=1

#1.449 ms ± 205.297 μs
@benchmark for i in 1:10000 swapsort(x) end setup=(x=rand(n)) evals=1

```

---

_[View the full topic](https://discourse.julialang.org/t/dispatching-by-values-is-very-slow-feature-or-problem/65586)._
