Skip to content

Instantly share code, notes, and snippets.

@aviatesk
Last active August 15, 2019 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aviatesk/c8c0a24d30051151433f44431e7f54f1 to your computer and use it in GitHub Desktop.
Save aviatesk/c8c0a24d30051151433f44431e7f54f1 to your computer and use it in GitHub Desktop.
isa vs. multiple dispatch branching
# %% defines
function isabranch(numsary)
s = 0
for (n1, n2) ∈ numsary
if n1 isa Int8 && n2 isa Int8
s += 1
elseif n1 isa Int8 && n2 isa Int16
s += 2
elseif n1 isa Int8 && n2 isa Int32
s += 3
elseif n1 isa Int16 && n2 isa Int8
s += 4
elseif n1 isa Int16 && n2 isa Int16
s += 5
elseif n1 isa Int16 && n2 isa Int32
s += 6
elseif n1 isa Int32 && n2 isa Int8
s += 7
elseif n1 isa Int32 && n2 isa Int16
s += 8
else
s += 9
end
end
s
end
mdbranch(numsary) = begin
s = 0
for (n1, n2) ∈ numsary
s += mdbranch(n1, n2)
end
s
end
mdbranch(::Int8, ::Int8) = 1
mdbranch(::Int8, ::Int16) = 2
mdbranch(::Int8, ::Int32) = 3
mdbranch(::Int16, ::Int8) = 4
mdbranch(::Int16, ::Int16) = 5
mdbranch(::Int16, ::Int32) = 6
mdbranch(::Int32, ::Int8) = 7
mdbranch(::Int32, ::Int16) = 8
mdbranch(::Int32, ::Int32) = 9
# %% setups
using BenchmarkTools
generate() = begin
n = 10000
nums = (Int8(1), Int16(1), Int32(1))
[rand(nums, 2) for _ ∈ 1:n]
end
testary = generate()
@assert isabranch(testary) == mdbranch(testary)
# %% benchmarks
b1 = @benchmark isabranch(numary) setup = (numary = generate())
b2 = @benchmark mdbranch(numary) setup = (numary = generate())
# %% results
@info "Branching by `isa`:"
b1 |> display
@info "Branching by multiple dispatch:"
b2 |> display
ans = open(@__FILE__) do file
read(file, String)
end
open(@__FILE__, "w") do file
"""
$(ans)
#=
Branching by `isa`:
$(repr("text/plain", b1))
Branching by multiple dispatch
$(repr("text/plain", b2))
=#
""" |> s -> write(file, s)
end
#=
Branching by `isa`:
BenchmarkTools.Trial:
memory estimate: 0 bytes
allocs estimate: 0
--------------
minimum time: 219.500 μs (0.00% GC)
median time: 273.199 μs (0.00% GC)
mean time: 294.917 μs (0.00% GC)
maximum time: 593.500 μs (0.00% GC)
--------------
samples: 1761
evals/sample: 1
Branching by multiple dispatch
BenchmarkTools.Trial:
memory estimate: 154.36 KiB
allocs estimate: 9879
--------------
minimum time: 1.191 ms (0.00% GC)
median time: 1.720 ms (0.00% GC)
mean time: 1.751 ms (0.46% GC)
maximum time: 4.215 ms (0.00% GC)
--------------
samples: 1170
evals/sample: 1
=#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment