Hi there,
I am new to Julia and very excited about it. One of the things I have been excited about (other than performance) is the multiple dispatch. So I figured I would eliminate many of jammed zillion of if-else statements I have in my code for smaller functions using multiple dispatch. So I did a little rough performance test to see what kind of overhead I would incur, and not only it took quite a bit longer, but it generated a large memory footprint:
0.074132 seconds (5 allocations: 176 bytes) #ifelse statement within loop
5.737640 seconds (200.00 M allocations: 2.980 GiB, 1.54% gc time) #type dispatch 1 within loop
6.612299 seconds (200.00 M allocations: 2.980 GiB, 1.39% gc time) #type dispatch 2 within loop
There is a good chance but I am probably doing something I am not supposed to, would certainly appreciate guidance. Thank you.
Here’s the code:
function test_if(N::Int,p::Int)
j = 0
for i=1:N
if p == 0
j += 1
p = 1
elseif p == 1
j += 2
p = 0
end
end
return j
end
test_if(10,0) #15
abstract type atype end
struct s1 <: atype end
struct s2 <: atype end
abstract type a1 <: atype end
abstract type a2 <: atype end
@inline function sum_j(j::Int,::Type{s1})::Int
return j+1
end
@inline function sum_j(j::Int,::Type{s2})::Int
return j+2
end
@inline function sum_j(j::Int,::Type{a1})::Int
return j+1
end
@inline function sum_j(j::Int,::Type{a2})::Int
return j+2
end
@inline function update_s(::Type{s1})::Type{s2}
return s2
end
@inline function update_s(::Type{s2})::Type{s1}
return s1
end
@inline function update_s(::Type{a1})::Type{a2}
return a2
end
@inline function update_s(::Type{a2})::Type{a1}
return a1
end
function test_struct(N::Int,p::Type{T}) where {T<:atype}
j = 0
for i=1:N
j = sum_j(j,p)
p = update_s(p)
end
return j
end
test_struct(10,a1) #15
N = 100000000
@time test_if(N,0)
@time test_struct(N,s1)
@time test_struct(N,a1)
which generates
0.074132 seconds (5 allocations: 176 bytes)
5.737640 seconds (200.00 M allocations: 2.980 GiB, 1.54% gc time)
6.612299 seconds (200.00 M allocations: 2.980 GiB, 1.39% gc time)
EDIT: Running Julia 0.6.0 on Windows.