# Allocations due to Boolean keyword arguments - how to avoid them?

**URL:** <https://discourse.julialang.org/t/allocations-due-to-boolean-keyword-arguments-how-to-avoid-them/87654>\
**Category:** Performance\
**Tags:** memory-allocation, val, boolean\
**Created:** [September 22, 2022, 2:43pm UTC](https://discourse.julialang.org/t/allocations-due-to-boolean-keyword-arguments-how-to-avoid-them/87654 "2022-09-22T14:43:04Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![Krastanov](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/krastanov/32/6817_2.png) [@Krastanov](https://discourse.julialang.org/u/Krastanov)\
**Post date:** [September 22, 2022, 3:37pm UTC](https://discourse.julialang.org/t/allocations-due-to-boolean-keyword-arguments-how-to-avoid-them/87654/4 "2022-09-22T15:37:15Z")

</div>

But then why is the second example working fine without allocations? Why is there no dynamic dispatch, even though it is the exact same flow of code?

I copy it here (it was in the `<details>` tag of the original post):

```julia
"""Just some contrived work function that happens to slightly change behavior depending on Val keyword"""
function simple_work_val(obj::Vector; extrawork::Val{B}=Val(true)) where B
    l = size(obj,1)
    @inbounds for i in 1:l
        @inbounds for j in i+1:l
            obj[i] ⊻= obj[j]
            if B
                obj[i] += obj[i]
            end
        end
    end
end

"""A "public interface" function that uses a Bool keyword instead of a Val keyword"""
function simple_work_bool_to_val(obj::Vector; extrawork::Bool=true)
    simple_work_val(obj; extrawork=Val(extrawork))
end

```

The reason for the `Val{true}` is that in the real non-minimal case it has noticeably different performance, presumably because it forces specialization. It is something I originally saw in [this thread](https://discourse.julialang.org/t/taking-ttfx-seriously-can-we-make-common-packages-faster-to-load-and-use/74949/15) with examples of its use in [SciML](https://github.com/SciML/OrdinaryDiffEq.jl/pull/1473/files#diff-8ce813ea8d7f370bc91b5ac1526a80f7fd354be769bafdd6b12b7368f3ae90a9L395) and [Polyester](https://github.com/JuliaSIMD/Polyester.jl/commit/5e6ae4c2ae009b507bbcf90ff2c2b9b7d5e94559#diff-a523f7f63af3c48f517501d7e392926093393f7d033fb208f477568ec30bec38L72). And here is a [real world example where simply switching from Bool to Val{Bool} eliminated allocations, because of this specialization issue](https://github.com/Krastanov/QuantumClifford.jl/commit/e8f94e95cc7b8d7a093a16f8022823daf5b8cb61) - the issue is that this example is rather long so I could not use it as a MWE.

---

_[View the full topic](https://discourse.julialang.org/t/allocations-due-to-boolean-keyword-arguments-how-to-avoid-them/87654)._
