Created
February 13, 2021 17:09
-
-
Save jebej/53b02ee9a888f17e74f3832486850aa1 to your computer and use it in GitHub Desktop.
julia abstract dispatch tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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