Skip to content

Avoid repeated union-splitting on oneof fields in generated encode methods - #316

Merged
quinnj-bot[bot] merged 1 commit into
JuliaIO:masterfrom
bachdavi:oneof-encode-perf
Nov 25, 2026
Merged

quinnj-bot[bot] merged 1 commit into
JuliaIO:masterfrom
bachdavi:oneof-encode-perf

Conversation

@bachdavi

Copy link
Copy Markdown
Contributor

Problem

With the default parametrize_oneofs=false, oneof fields are generated with a non-concrete type, e.g.

struct PrimitiveValue
    tag::PrimitiveType.T
    value::Union{Nothing,OneOf{<:Union{Int64,Int32,UInt64,UInt32,Float64,Float32,Bool,Vector{UInt8}}}}
end

and the generated PB.encode / PB._encoded_size methods look like

    if isnothing(x.value);
    elseif x.value.name === :int64_val
        PB.encode(e, 3, x.value[]::Int64)
    ...
    end

Every x.value read followed by a call (including isnothing(...) — v === nothing is a builtin and does not have this problem) makes Julia union-split Union{Nothing,OneOf{<:Union{...}}}, i.e. emit a runtime isa(v, OneOf{<:Union{...}}) check. That check goes through the general subtyping algorithm (ijl_subtype_env / _forall_exists_subtype) and is very slow. In a profile of a real workload ~77% of serialization time was spent there.

Fix

Read the oneof field once into a local, test it with ===, and compare against its name bound once. The locals live in a let block so they can't clash with other generated code or other oneofs in the same message:

function PB.encode(e::PB.AbstractProtoEncoder, x::A)
    initpos = position(e.io)
    let oneof = x.a, oneof_name = oneof === nothing ? nothing : oneof.name
        if oneof === nothing;
        elseif oneof_name === :b
            PB.encode(e, 1, oneof[]::Int32)
        elseif oneof_name === :c
            PB.encode(e, 2, oneof[]::Int64, Val{:zigzag})
        end
    end
    return position(e.io) - initpos
end

Same for PB._encoded_size. The generated code is the same for parametrize_oneofs=true and false (and force_required oneofs, where the === nothing check is just constant-false).

Numbers (Julia 1.10.4)

On 1M values (half Int64, half string) of a PrimitiveValue-like message:

encode ns/value
before (parametrize_oneofs=false) 6136
parametrize_oneofs=true (before this change) 178 (but decode ~4x slower)
after (parametrize_oneofs=false) 88

Output is byte-identical. A smaller standalone benchmark (7-variant oneof, 1M values) with this branch vs master: encode 1293 → 74 ns/value, _encoded_size 1226 → 27 ns/value, identical bytes.

Notes

  • Non-oneof optional message fields still use !isnothing(x.f) && PB.encode(e, n, x.f). For the usual Union{Nothing,B} with concrete B this is cheap (small concrete union), so I left them alone; they could only be affected when B is itself a non-concrete (parametrized-oneof stub) type.
  • Added a codegen snapshot test for oneof encode / _encoded_size covering both parametrize_oneofs settings. Full test suite passes locally.

…thods

Non-parametrized oneof fields have a non-concrete type such as
`Union{Nothing,OneOf{<:Union{Int32,String}}}`. The generated `PB.encode`
and `PB._encoded_size` methods read `x.<oneof>` in every branch and call
`isnothing` on it, each of which makes Julia union-split with a runtime
`isa(v, OneOf{<:Union{...}})` check that goes through the general (slow)
subtyping algorithm.

Read the oneof field once into a local inside a `let` block, test it
with the `===` builtin and compare against its `name` bound once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.19%. Comparing base (23b1713) to head (645c412).
⚠️ Report is 7 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #316      +/-   ##
==========================================
+ Coverage   93.59%   94.19%   +0.60%     
==========================================
  Files          25       25              
  Lines        3093     3120      +27     
==========================================
+ Hits         2895     2939      +44     
+ Misses        198      181      -17     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bachdavi

Copy link
Copy Markdown
Contributor Author

@quinnj Are you the right person to have a look at this? Thank you!

@quinnj-bot quinnj-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[review generated via AI] Thanks @bachdavi, this looks right and it measurably helps.

Correctness. After if oneof === nothing, Julia narrows the local oneof to the OneOf{...} part of the union without a runtime isa. So oneof.name and oneof[] are plain calls with no subtype check, which is the slow path you saw in your profile. Each branch still sees the same value as before, and the output bytes are identical (checked below).

Measured on Julia 1.12.6, with a message that has an 8-way oneof (int64/int32/uint64/uint32/double/float/bool/bytes) and a repeated field of 80,000 of them:

median encode
master 6.4 s
this PR 6.5 s
master + the truncate fix below 23 ms
this PR + the truncate fix below 4.6 ms

The first two rows are dominated by a separate problem I found while benchmarking. On Julia 1.12+, _with_size grows the buffer with truncate, and Base's truncate copies the whole buffer each time it grows it, so encoding a repeated field is quadratic in its length. I'll open a separate PR for that. With it in place, this PR makes encoding about 5x faster on this workload.

One non-blocking thought: the generated let introduces the locals oneof and oneof_name. A oneof member whose Julia type name is literally oneof would be shadowed inside the let. That's very unlikely, so I don't think it's worth changing.

🤖 Generated with Claude Code

@quinnj-bot
quinnj-bot Bot merged commit 8ec6d8e into JuliaIO:master Nov 25, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant