# Branch in dispatch on values

**URL:** https://discourse.julialang.org/t/branch-in-dispatch-on-values/37465
**Category:** General Usage
**Tags:** dispatch
**Created:** [April 12, 2020, 9:28pm UTC](https://discourse.julialang.org/t/branch-in-dispatch-on-values/37465 "2020-04-12T21:28:01Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![mforets](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mforets/32/298_2.png) [@mforets](https://discourse.julialang.org/u/mforets)
#### Post date: [April 12, 2020, 9:28pm UTC](https://discourse.julialang.org/t/branch-in-dispatch-on-values/37465/1 "2020-04-12T21:28:01Z")

</div>

This has probably been discussed elsewhere, but I didn’t find it. Why do the runtimes of `foo` and `bar` functions below differ? Since `w` is constrained to be a boolean, I didn’t expect to see such a huge difference.

Let

```julia
function foo(x, w::Bool=true)
   _foo(x, Val(w)) 
end

_foo(x, ::Val{true}) = sum(exp.(x))
_foo(x, ::Val{false}) = sum(exp.(-x))

x = rand(10);

@btime foo($x)
@btime foo($x, true)
@btime foo($x, false)

  4.489 μs (1 allocation: 160 bytes)
  4.431 μs (1 allocation: 160 bytes)
  4.603 μs (2 allocations: 320 bytes)
5.962627209972655

```

Compare with:

```julia
function bar(x, w::Bool=true)
    if w
        return _foo(x, Val(true))
    else
        return _foo(x, Val(false))
    end
end

@btime bar($x)
@btime bar($x, true)
@btime bar($x, false)

  83.225 ns (1 allocation: 160 bytes)
  83.142 ns (1 allocation: 160 bytes)
  121.367 ns (2 allocations: 320 bytes)
5.962627209972655

```

---

<div class="post-metadata">

### Author: ![Oscar\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oscar_smith/32/25343_2.png) [@Oscar\_Smith](https://discourse.julialang.org/u/Oscar_Smith)
#### Post date: [April 12, 2020, 9:33pm UTC](https://discourse.julialang.org/t/branch-in-dispatch-on-values/37465/2 "2020-04-12T21:33:12Z")

</div>

`bar` is type stable, so no dispatch happens at run-time. Only an if statement. `foo` has dynamic dispatch which is slower. Theoretically, the compiler eventually could deal with this, but it’s hard to do in general.

---

<div class="post-metadata">

### Author: ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)
#### Post date: [April 12, 2020, 9:37pm UTC](https://discourse.julialang.org/t/branch-in-dispatch-on-values/37465/3 "2020-04-12T21:37:08Z")

</div>

> [@mforets](#):
>
> Since `w` is constrained to be a boolean,

There isn’t a special case for that ATM
