Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
julia abstract dispatch tests
using BenchmarkTools
abstract type AbstrType end
struct ConcrType1 <: AbstrType; x::Int; end
struct ConcrType2 <: AbstrType; x::Int; end
@noinline f(a::ConcrType1)::Int = a.x
@noinline f(a::ConcrType2)::Int = a.x
n = 1_000_000
arrconcr = [ConcrType1(i) for i=1:n]
arrabstr = AbstrType[rand(Bool) ? ConcrType1(i) : ConcrType2(i) for i=1:n]
arrunion = Union{ConcrType1, ConcrType2}[rand(Bool) ? ConcrType1(i) : ConcrType2(i) for i=1:n]
function fun_auto(A)
sum_arr = 0
for i = 1:length(A)
@inbounds sum_arr += f(A[i])
end
return sum_arr
end
function fun_manual(A)
# manual dispatch
sum_arr = 0
for i = 1:length(A)
@inbounds a = A[i]
T = typeof(a)
if T === ConcrType1
sum_arr += f(a::ConcrType1)
elseif T === ConcrType2
sum_arr += f(a::ConcrType2)
else
sum_arr += f(a)
end
end
return sum_arr
end
println("\n\n## concrete array (baseline):")
display(@benchmark fun_auto($arrconcr))
println("\n\n## auto dispatch on abstract array:")
display(@benchmark fun_auto($arrabstr))
println("\n\n## auto dispatch on union array:")
display(@benchmark fun_auto($arrunion))
println("\n\n## manual dispatch on abstract array:")
display(@benchmark fun_manual($arrabstr))
println("\n\n## manual dispatch on union array:")
display(@benchmark fun_manual($arrunion))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment