Skip to content

Instantly share code, notes, and snippets.

@tk3369
Created April 30, 2021 22:21
Show Gist options
  • Save tk3369/790b10b4ea34aff6532b23f15b278744 to your computer and use it in GitHub Desktop.
Save tk3369/790b10b4ea34aff6532b23f15b278744 to your computer and use it in GitHub Desktop.

Set up test data

julia> bs = rand(Bool, 100000);

Using if/else:

julia> function foo(bs)
           s = 0
           for b in bs
               if b
                   s += foo2()
               else
                   s += foo3()
               end
           end
           return s
       end
foo (generic function with 1 method)

julia> foo2() = 1
foo2 (generic function with 1 method)

julia> foo3() = -1
foo3 (generic function with 1 method)

julia> @btime foo($bs)
  27.500 μs (0 allocations: 0 bytes)
-280

Using dynamic dispatch

julia> function bar(bs)
           s = 0
           for b in bs
               s += bar(b)
           end
           return s
       end
bar (generic function with 4 methods)

julia> bar(b::Bool) = bar(Val(b))
bar (generic function with 4 methods)

julia> bar(::Val{true}) = 1
bar (generic function with 4 methods)

julia> bar(::Val{false}) = -1
bar (generic function with 4 methods)

julia> @btime bar($bs)
  18.420 ms (0 allocations: 0 bytes)
-280
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment