Hi, I’m evaluating Julia to replace some old C++ code. The code uses inheritance where there is a single base class and lots (100’s) of derived classes. There are a large number of instances, and the code needs to be able to quickly get a base class field from a derived instance.
I know that Julia does not have field inheritance and uses multiple dispatch to access data on abstract types instead. However, I’ve noticed that multiple dispatch methods slow down quite a bit for my use case when many implementations of the method are added. I’ve created some basic code to illustrate my point:
abstract type Car end
struct HondaAccord <: Car
length::Int64
end
struct ToyotaCamry1 <: Car
length::Int64
end
struct ToyotaCamry2 <: Car
length::Int64
end
function getLength(a::T)::Int64 where T <: Car
a.length
end
function speedTest()
cars = Car[]
while length(cars) < 10000
push!(cars, HondaAccord(100))
push!(cars, ToyotaCamry1(100))
push!(cars, ToyotaCamry2(100))
end
sum = 0::Int64
for j = 1:10000
for i = 1:length(cars)
sum = sum + getLength(cars[i])
end
end
println(sum)
end
As you add additional Toyota Camrys (ToyotaCamry3, 4, 5, etc), it starts slowing down more and more. I’m assuming this is because of the way multiple dispatch is implemented.
My question is this: if you know that the layout of every derived class starts the same way (i.e., has the same the “inherited” fields), is there some way to access those fields without going through multiple dispatch (even if it is unsafe)? Thanks!