Next trial;)
using BenchmarkTools
abstract type AbstractType end
struct ConcreteSingleton1 <: AbstractType end
struct ConcreteSingleton2 <: AbstractType end
struct ConcreteSingleton3 <: AbstractType end
mutable struct MyStruct1
x :: Int
consin :: AbstractType
end
mutable struct MyStruct2
x :: Int
consin :: Type
end
mutable struct MyStruct3
x :: Int
consin :: ConcreteSingleton1
end
#sum ints
function f(vs)
vsum = 0
for v in vs
if v.consin isa ConcreteSingleton1
cs1 = v.consin
vsum += v.x + fs(cs1)
elseif v.consin isa ConcreteSingleton2
cs2 = v.consin
vsum += v.x + fs(cs2)
elseif v.consin isa ConcreteSingleton3
cs3 = v.consin
vsum += v.x + fs(cs3)
else
@assert false
end
end
return vsum
end
function f(vs::Vector{MyStruct2})
vsum = 0
for v in vs
if v.consin isa Type{ConcreteSingleton1}
vsum += v.x + fs(ConcreteSingleton1)
elseif v.consin isa Type{ConcreteSingleton2}
vsum += v.x + fs(ConcreteSingleton2)
elseif v.consin isa Type{ConcreteSingleton3}
vsum += v.x + fs(ConcreteSingleton3)
else
@assert false
end
end
return vsum
end
fs(a) = 0
fs(cs1::ConcreteSingleton1) = 1
fs(cs1::ConcreteSingleton2) = 2
fs(cs1::ConcreteSingleton3) = 3
fs(cs1::Type{ConcreteSingleton1}) = 1
fs(cs1::Type{ConcreteSingleton2}) = 2
fs(cs1::Type{ConcreteSingleton3}) = 3
mystructs1 = fill(MyStruct1(1, ConcreteSingleton1()), 1000);
mystructs2 = fill(MyStruct2(1, ConcreteSingleton1), 1000);
mystructs3 = fill(MyStruct3(1, ConcreteSingleton1()), 1000);
@btime f(mystructs1)
@btime f(mystructs2)
@btime f(mystructs3)
yielding
45.100 μs (745 allocations: 11.64 KiB)
984.615 ns (1 allocation: 16 bytes)
521.466 ns (1 allocation: 16 bytes)
Inspired by this announcement, still not sure if this helps…
Edit: fixing significant mistakes…