-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Description
The benchmark example in the README file suggests that sum types are faster than unions. In the following minimal modification of that example it's suddenly 5x slower.
using LightSumTypes, Chairmarks
struct A end
struct B x::Int end; B() = B(0)
struct C end
struct D end
struct E end
struct F end
const U = Union{A, B, C, D, E, F}
@sumtype S(A, B, C, D, E, F)
f(::A) = 1
f(::B) = 2
f(::C) = 3
f(::D) = 4
f(::E) = 5
f(::F) = 6
f(s::S) = f(variant(s))
vec_manytypes = collect(U, rand((A(), B(), C(), D(), E(), F()), 1000));
iter_manytypes = (x for x in vec_manytypes);
vec_sumtypes = map(S, vec_manytypes);
iter_sumtypes = (x for x in vec_sumtypes);
julia> @b sum(f, $vec_manytypes), sum(f, $vec_sumtypes)
(462.444 ns, 2.412 μs)
julia> @b sum(f, $iter_manytypes), sum(f, $iter_sumtypes)
(1.706 μs, 2.165 μs)
If A
has the x
field and not B
, then the timings change:
julia> @b sum(f, $vec_manytypes), sum(f, $vec_sumtypes)
(466.571 ns, 828.714 ns)
julia> @b sum(f, $iter_manytypes), sum(f, $iter_sumtypes)
(1.603 μs, 541.417 ns)
Same for F
instead of B
. So the potential benefits of sum types seems to be very fragile. Is this a bug, or can one otherwise say what to do in order to get better performance?
Status `/tmp/jl_aYOKNY/Project.toml`
[0ca39b1e] Chairmarks v1.3.1
[f56206fc] LightSumTypes v5.2.0
Julia Version 1.11.4
Commit 8561cc3d68d (2025-03-10 11:36 UTC)
Build Info:
Official https://julialang.org/ release
Platform Info:
OS: Linux (x86_64-linux-gnu)
CPU: 4 × Intel(R) Core(TM) i3-10110U CPU @ 2.10GHz
WORD_SIZE: 64
LLVM: libLLVM-16.0.6 (ORCJIT, skylake)
Threads: 1 default, 0 interactive, 1 GC (on 4 virtual cores)
Metadata
Metadata
Assignees
Labels
No labels