JuliaDynamics / JuliaDynamics/LightSumTypes.jl
sum types can be much slower than unions
Nobody has claimed this yet.
- Dominant language
- Julia
- Stars
- 62
- Forks
- 2
- PR merge metrics
- No merged PRs in 30d
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)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the README benchmark with the provided Julia 1.11.4 example, comparing the Union and @sumtype S cases for vectors and iterators. Inspect the generated sum-type dispatch around variant(s) and determine why field placement changes the timings; done means identifying the cause and fixing the regression or documenting the conditions and recommended usage.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- julia
- Domain
- performance
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100