← Back to Pull requests

sorting short homogeneous tuples: avoid allocation for more tuple lengths #60951

Open
nsajko opened this pull request with 46 lines diff across 2 files
View on GitHub
nsajko nsajko commented on Feb 06, 2026 14:12 UTC
Author

For lengths over the limit where recursion is used, but small enough for insertion sort to be competitive, use a simple in-place insertion sort on a Memory value, while allowing the elimination of the heap allocation.

Context:

The feature for sorting homogeneous tuples originates with PR #54494.

Approach originally proposed back in 2024, but then forgot to make a PR until now:

https://github.com/JuliaLang/julia/pull/54494#pullrequestreview-2487075219

https://github.com/JuliaLang/julia/pull/55913#issuecomment-2514664145

https://github.com/JuliaLang/julia/pull/56847#issuecomment-2562010714

Already used a similar approach in a PR to implement shuffle(::NTuple):

* https://github.com/JuliaLang/julia/pull/56906

Diff: 46 lines (+43 / -3) across 2 files Reviewer: nsajko Review duration: 415404m
All Vouch review confidence checks passed
Residual risk 0.09 = Change Risk (0.48) × (1 − Review Confidence (0.81)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.48 · 46 lines diff across 2 files
0.48
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.93 · 5 substantive comment(s)
0.93
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
81%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.230
Self Review self_review
0.140
Real PR Conversation Timeline
16 items
KristofferC KristofferC commented on Feb 06, 2026 14:17 UTC
Contributor

Is there a drawback to copy pasting the code in https://github.com/JeffreySarnoff/SortingNetworks.jl?

nsajko nsajko commented on Feb 06, 2026 14:33 UTC
Author

@KristofferC one issue is that sorting networks are not stable

Or rather, a stable sorting network would be huge so would not be efficient, which is why stable sorting networks are not used.

Additionally, in my experience, optimal sorting networks do not have much of a performance advantage over more general algorithmic (not hardcoded) unstable sorting approaches.

An issue with SortingNetworks.jl specifically, is that it is not up-to-date with the best known sorting networks, as far as I remember. My own package OptimalSortingNetworks.jl should be better in that regard. Also see TupleSorting.jl. Not to mention the extremely manual approach of SortingNetworks.jl resists maintainability.

nsajko nsajko commented on Feb 06, 2026 14:43 UTC
Author

Not sure why the whitespace check was cancelled.

nsajko nsajko commented on Feb 06, 2026 16:40 UTC
Author

Benchmark script:

const samples = parse(Int, ARGS[1])
const evals = parse(Int, ARGS[2])
const max_len = 16

@show samples
@show evals
println()
flush(stdout)

using BenchmarkTools

println("case: sorted")
flush(stdout)

for n ∈ 0:max_len
    tup = ntuple(identity, n)
    @btime sort($tup) seconds=Inf samples=samples evals=evals
end

println("case: reverse sorted")
flush(stdout)

# reverse sorted
for n ∈ 0:max_len
    tup = reverse(ntuple(identity, n))
    @btime sort($tup) seconds=Inf samples=samples evals=evals
end

Git branch master:

$ ./julia-e9a67a8473/bin/julia /tmp/b.jl 10000 30
samples = 10000
evals = 30

case: sorted
  1.667 ns (0 allocations: 0 bytes)
  3.000 ns (0 allocations: 0 bytes)
  3.333 ns (0 allocations: 0 bytes)
  3.667 ns (0 allocations: 0 bytes)
  4.000 ns (0 allocations: 0 bytes)
  4.667 ns (0 allocations: 0 bytes)
  6.000 ns (0 allocations: 0 bytes)
  7.333 ns (0 allocations: 0 bytes)
  8.000 ns (0 allocations: 0 bytes)
  14.667 ns (0 allocations: 0 bytes)
  30.700 ns (2 allocations: 144 bytes)
  31.367 ns (2 allocations: 144 bytes)
  35.033 ns (2 allocations: 160 bytes)
  33.367 ns (2 allocations: 160 bytes)
  40.367 ns (2 allocations: 176 bytes)
  43.400 ns (2 allocations: 176 bytes)
  38.733 ns (2 allocations: 192 bytes)
case: reverse sorted
  1.667 ns (0 allocations: 0 bytes)
  3.000 ns (0 allocations: 0 bytes)
  3.333 ns (0 allocations: 0 bytes)
  3.667 ns (0 allocations: 0 bytes)
  4.000 ns (0 allocations: 0 bytes)
  5.333 ns (0 allocations: 0 bytes)
  6.000 ns (0 allocations: 0 bytes)
  7.000 ns (0 allocations: 0 bytes)
  7.333 ns (0 allocations: 0 bytes)
  15.000 ns (0 allocations: 0 bytes)
  46.067 ns (2 allocations: 144 bytes)
  55.067 ns (2 allocations: 144 bytes)
  57.767 ns (2 allocations: 160 bytes)
  66.100 ns (2 allocations: 160 bytes)
  67.100 ns (2 allocations: 176 bytes)
  74.433 ns (2 allocations: 176 bytes)
  96.500 ns (2 allocations: 192 bytes)

PR branch:

$ ./julia-e96f5d4735/bin/julia /tmp/b.jl 10000 30
samples = 10000
evals = 30

case: sorted
  1.667 ns (0 allocations: 0 bytes)
  2.667 ns (0 allocations: 0 bytes)
  9.333 ns (0 allocations: 0 bytes)
  10.000 ns (0 allocations: 0 bytes)
  10.667 ns (0 allocations: 0 bytes)
  11.667 ns (0 allocations: 0 bytes)
  12.667 ns (0 allocations: 0 bytes)
  13.333 ns (0 allocations: 0 bytes)
  15.000 ns (0 allocations: 0 bytes)
  15.333 ns (0 allocations: 0 bytes)
  18.667 ns (0 allocations: 0 bytes)
  23.367 ns (0 allocations: 0 bytes)
  20.700 ns (0 allocations: 0 bytes)
  22.033 ns (0 allocations: 0 bytes)
  25.700 ns (0 allocations: 0 bytes)
  22.700 ns (0 allocations: 0 bytes)
  43.400 ns (2 allocations: 192 bytes)
case: reverse sorted
  1.667 ns (0 allocations: 0 bytes)
  2.667 ns (0 allocations: 0 bytes)
  9.333 ns (0 allocations: 0 bytes)
  10.667 ns (0 allocations: 0 bytes)
  12.333 ns (0 allocations: 0 bytes)
  13.667 ns (0 allocations: 0 bytes)
  16.000 ns (0 allocations: 0 bytes)
  19.700 ns (0 allocations: 0 bytes)
  21.367 ns (0 allocations: 0 bytes)
  23.700 ns (0 allocations: 0 bytes)
  32.367 ns (0 allocations: 0 bytes)
  35.400 ns (0 allocations: 0 bytes)
  38.067 ns (0 allocations: 0 bytes)
  57.433 ns (0 allocations: 0 bytes)
  46.767 ns (0 allocations: 0 bytes)
  54.067 ns (0 allocations: 0 bytes)
  82.133 ns (2 allocations: 192 bytes)

Interpretation: the PR is not a straight win yet. Some re-tuning of tuple length thresholds may be good.

nsajko nsajko commented on code on Feb 06, 2026 16:44 UTC
Code Review
base/sort.jl:1
@@ -1784,6 +1784,45 @@ sort(v::AbstractVector; kws...) = sort!(copymutable(v); kws...)
 const COLLECT_ON_SORT_TYPES = Union{Base.KeySet, Base.ValueIterator}
 sort(v::COLLECT_ON_SORT_TYPES; kws...) = sort!(collect(v); kws...)
 
+function _tuple_insertion_sort(tup::Tuple, ordering::Ordering)
+    # Use `@assume_effects` to allow constant folding.
+    #
+    # Keep everything inlined into one function to allow escape analysis to prove
+    # `mem` does not escape. Then the heap allocation should be eliminated. At time
+    # of writing, Julia does not have interprocedural escape analysis. Once
+    # interprocedural escape analysis is implemented, it may be possible to simplify
+    # the code in this method body.
+    @inline let
+        n = length(tup)
+        elt = eltype(tup)
+        T = Memory{elt}
+        mem = T(undef, n)
+        Base.@assume_effects :terminates_locally for i ∈ eachindex(mem)  # copy `tup` to `mem`
+            x = tup[i]
+            Base.@assume_effects :consistent mem[i] = x
+        end
+        Base.@assume_effects :terminates_locally for i ∈ eachindex(mem)[begin:(end - 1)]  # insertion sort `mem`
+            x = Base.@assume_effects :consistent mem[i + 1]
+            j = i
+            while firstindex(mem) ≤ j
+                y = Base.@assume_effects :consistent mem[j]
+                if !(Order.lt(ordering, x, y)::Bool)
+                    break
+                end
+                k = j + 1
+                Base.@assume_effects :consistent mem[k] = y
+                j = j - 1
+            end
+            l = j + 1
+            Base.@assume_effects :consistent mem[l] = x
+        end

If Julia had interprocedural escape analysis (and stronger effect inference?), we could simply do something like this:

        sort!(mem; ord = ordering)

nsajko nsajko commented on Feb 06, 2026 16:54 UTC
Author

To investigate: are the disappointing benchmark results due to the overhead of creating a MemoryRef? If so, an approach to achieving better performance might be to introduce a simple new type (not public). Something like this:

mutable struct FixedSizeVector{T} <: AbstractVector{T}  # or `DenseVector{T}`
    const m::MemoryRef{T}
end
# ... a few methods

EDIT: no, does not help

JeffBezanson JeffBezanson commented on Feb 06, 2026 21:58 UTC
Contributor

Would it make sense to call the existing sort! function instead of re-implementing insertion sort?

nsajko nsajko commented on Feb 06, 2026 22:10 UTC
Author

@JeffBezanson I believe that would cause the allocation not to be eliminated, due to the current lack of interprocedural escape analysis. This is already mentioned in the comments in the source code and in a message above.

LilithHafner LilithHafner commented on Feb 07, 2026 12:59 UTC
Contributor

When you're bench-marking, I recommend looking primarily at unsorted inputs, with performance on sorted and reverse sorted inputs a secondary concern. Optimizing julia for people who are bottlenecked on calling sort on already-sorted collections is IMO not a top priority. Especially compared to optimizing for folks who are bottlenecked on actual sorting.

I'd also say, as the original implementer of this tuple version: it's great that you're re-implementing it. Thank you. That implementation was never intended to have optimal performance. "Good enough" was my target, and I was more concerned with API than performance.

nsajko nsajko commented on Feb 10, 2026 08:46 UTC
Author

Benchmark script:

const samples = parse(Int, ARGS[1])
const evals = parse(Int, ARGS[2])
const max_len = parse(Int, ARGS[3])

@show samples
@show evals
@show max_len

println()
flush(stdout)

using BenchmarkTools

for elt ∈ (Int16, Float32, Int128)
    @show elt
    for n ∈ 0:max_len
        print("  ")
        @show n
        tup = (rand(elt, n)...,)
        print("  ")
        @btime sort($tup) seconds=Inf samples=samples evals=evals
    end
end

using InteractiveUtils
versioninfo()

Results for Git branch master:

samples = 50000
evals = 30
max_len = 21

elt = Int16
  n = 0
    1.667 ns (0 allocations: 0 bytes)
  n = 1
    3.000 ns (0 allocations: 0 bytes)
  n = 2
    3.333 ns (0 allocations: 0 bytes)
  n = 3
    3.333 ns (0 allocations: 0 bytes)
  n = 4
    4.000 ns (0 allocations: 0 bytes)
  n = 5
    5.333 ns (0 allocations: 0 bytes)
  n = 6
    6.333 ns (0 allocations: 0 bytes)
  n = 7
    7.333 ns (0 allocations: 0 bytes)
  n = 8
    8.667 ns (0 allocations: 0 bytes)
  n = 9
    15.000 ns (0 allocations: 0 bytes)
  n = 10
    36.067 ns (2 allocations: 80 bytes)
  n = 11
    42.733 ns (2 allocations: 80 bytes)
  n = 12
    53.433 ns (2 allocations: 80 bytes)
  n = 13
    49.100 ns (2 allocations: 96 bytes)
  n = 14
    47.067 ns (2 allocations: 96 bytes)
  n = 15
    66.133 ns (2 allocations: 96 bytes)
  n = 16
    68.133 ns (2 allocations: 96 bytes)
  n = 17
    88.133 ns (2 allocations: 96 bytes)
  n = 18
    74.133 ns (2 allocations: 96 bytes)
  n = 19
    80.133 ns (2 allocations: 96 bytes)
  n = 20
    88.833 ns (2 allocations: 96 bytes)
  n = 21
    107.867 ns (2 allocations: 112 bytes)
elt = Float32
  n = 0
    1.667 ns (0 allocations: 0 bytes)
  n = 1
    2.667 ns (0 allocations: 0 bytes)
  n = 2
    3.000 ns (0 allocations: 0 bytes)
  n = 3
    4.333 ns (0 allocations: 0 bytes)
  n = 4
    6.667 ns (0 allocations: 0 bytes)
  n = 5
    11.333 ns (0 allocations: 0 bytes)
  n = 6
    14.000 ns (0 allocations: 0 bytes)
  n = 7
    21.700 ns (0 allocations: 0 bytes)
  n = 8
    29.367 ns (0 allocations: 0 bytes)
  n = 9
    43.067 ns (0 allocations: 0 bytes)
  n = 10
    59.767 ns (2 allocations: 96 bytes)
  n = 11
    63.767 ns (2 allocations: 112 bytes)
  n = 12
    75.467 ns (2 allocations: 112 bytes)
  n = 13
    79.467 ns (2 allocations: 112 bytes)
  n = 14
    82.133 ns (2 allocations: 112 bytes)
  n = 15
    92.833 ns (2 allocations: 128 bytes)
  n = 16
    96.200 ns (2 allocations: 128 bytes)
  n = 17
    107.200 ns (2 allocations: 128 bytes)
  n = 18
    123.200 ns (2 allocations: 128 bytes)
  n = 19
    110.533 ns (2 allocations: 144 bytes)
  n = 20
    112.200 ns (2 allocations: 144 bytes)
  n = 21
    134.933 ns (2 allocations: 144 bytes)
elt = Int128
  n = 0
    1.667 ns (0 allocations: 0 bytes)
  n = 1
    2.667 ns (0 allocations: 0 bytes)
  n = 2
    3.000 ns (0 allocations: 0 bytes)
  n = 3
    6.000 ns (0 allocations: 0 bytes)
  n = 4
    7.333 ns (0 allocations: 0 bytes)
  n = 5
    10.667 ns (0 allocations: 0 bytes)
  n = 6
    13.333 ns (0 allocations: 0 bytes)
  n = 7
    15.000 ns (0 allocations: 0 bytes)
  n = 8
    18.367 ns (0 allocations: 0 bytes)
  n = 9
    29.700 ns (0 allocations: 0 bytes)
  n = 10
    55.100 ns (2 allocations: 224 bytes)
  n = 11
    60.767 ns (2 allocations: 240 bytes)
  n = 12
    70.800 ns (2 allocations: 256 bytes)
  n = 13
    77.800 ns (2 allocations: 272 bytes)
  n = 14
    79.833 ns (2 allocations: 288 bytes)
  n = 15
    77.800 ns (2 allocations: 304 bytes)
  n = 16
    105.200 ns (2 allocations: 320 bytes)
  n = 17
    99.167 ns (2 allocations: 336 bytes)
  n = 18
    120.233 ns (2 allocations: 368 bytes)
  n = 19
    124.233 ns (2 allocations: 368 bytes)
  n = 20
    127.567 ns (2 allocations: 400 bytes)
  n = 21
    146.967 ns (2 allocations: 400 bytes)
Julia Version 1.14.0-DEV.1699
Commit 9484a920291 (2026-02-10 01:46 UTC)
Build Info:
  Official https://julialang.org release
Platform Info:
  OS: Linux (x86_64-linux-gnu)
  CPU: 8 × AMD Ryzen 3 5300U with Radeon Graphics
  WORD_SIZE: 64
  LLVM: libLLVM-20.1.8 (ORCJIT, znver2)
  GC: Built with stock GC
Threads: 8 default, 1 interactive, 8 GC (on 8 virtual cores)
Environment:
  JULIA_NUM_PRECOMPILE_TASKS = 2
  JULIA_PKG_PRECOMPILE_AUTO = 0

Results for PR branch:

samples = 50000
evals = 30
max_len = 21

elt = Int16
  n = 0
    1.667 ns (0 allocations: 0 bytes)
  n = 1
    3.000 ns (0 allocations: 0 bytes)
  n = 2
    3.000 ns (0 allocations: 0 bytes)
  n = 3
    3.333 ns (0 allocations: 0 bytes)
  n = 4
    4.000 ns (0 allocations: 0 bytes)
  n = 5
    5.333 ns (0 allocations: 0 bytes)
  n = 6
    6.333 ns (0 allocations: 0 bytes)
  n = 7
    7.333 ns (0 allocations: 0 bytes)
  n = 8
    8.667 ns (0 allocations: 0 bytes)
  n = 9
    14.667 ns (0 allocations: 0 bytes)
  n = 10
    22.367 ns (0 allocations: 0 bytes)
  n = 11
    25.700 ns (0 allocations: 0 bytes)
  n = 12
    31.033 ns (0 allocations: 0 bytes)
  n = 13
    32.700 ns (0 allocations: 0 bytes)
  n = 14
    31.733 ns (0 allocations: 0 bytes)
  n = 15
    39.067 ns (0 allocations: 0 bytes)
  n = 16
    38.733 ns (0 allocations: 0 bytes)
  n = 17
    63.100 ns (0 allocations: 0 bytes)
  n = 18
    57.100 ns (0 allocations: 0 bytes)
  n = 19
    62.100 ns (0 allocations: 0 bytes)
  n = 20
    82.467 ns (0 allocations: 0 bytes)
  n = 21
    88.833 ns (2 allocations: 112 bytes)
elt = Float32
  n = 0
    1.667 ns (0 allocations: 0 bytes)
  n = 1
    2.667 ns (0 allocations: 0 bytes)
  n = 2
    3.333 ns (0 allocations: 0 bytes)
  n = 3
    4.667 ns (0 allocations: 0 bytes)
  n = 4
    6.667 ns (0 allocations: 0 bytes)
  n = 5
    11.000 ns (0 allocations: 0 bytes)
  n = 6
    13.333 ns (0 allocations: 0 bytes)
  n = 7
    20.700 ns (0 allocations: 0 bytes)
  n = 8
    25.033 ns (0 allocations: 0 bytes)
  n = 9
    42.733 ns (0 allocations: 0 bytes)
  n = 10
    40.067 ns (0 allocations: 0 bytes)
  n = 11
    47.400 ns (0 allocations: 0 bytes)
  n = 12
    44.433 ns (0 allocations: 0 bytes)
  n = 13
    70.467 ns (0 allocations: 0 bytes)
  n = 14
    82.467 ns (0 allocations: 0 bytes)
  n = 15
    94.500 ns (0 allocations: 0 bytes)
  n = 16
    83.467 ns (0 allocations: 0 bytes)
  n = 17
    119.200 ns (0 allocations: 0 bytes)
  n = 18
    118.867 ns (0 allocations: 0 bytes)
  n = 19
    132.900 ns (0 allocations: 0 bytes)
  n = 20
    139.933 ns (0 allocations: 0 bytes)
  n = 21
    158.967 ns (2 allocations: 144 bytes)
elt = Int128
  n = 0
    1.667 ns (0 allocations: 0 bytes)
  n = 1
    3.333 ns (0 allocations: 0 bytes)
  n = 2
    3.333 ns (0 allocations: 0 bytes)
  n = 3
    6.000 ns (0 allocations: 0 bytes)
  n = 4
    7.333 ns (0 allocations: 0 bytes)
  n = 5
    10.333 ns (0 allocations: 0 bytes)
  n = 6
    14.000 ns (0 allocations: 0 bytes)
  n = 7
    15.667 ns (0 allocations: 0 bytes)
  n = 8
    18.367 ns (0 allocations: 0 bytes)
  n = 9
    28.367 ns (0 allocations: 0 bytes)
  n = 10
    29.367 ns (0 allocations: 0 bytes)
  n = 11
    43.067 ns (0 allocations: 0 bytes)
  n = 12
    54.433 ns (0 allocations: 0 bytes)
  n = 13
    51.067 ns (0 allocations: 0 bytes)
  n = 14
    41.733 ns (0 allocations: 0 bytes)
  n = 15
    70.433 ns (0 allocations: 0 bytes)
  n = 16
    67.433 ns (0 allocations: 0 bytes)
  n = 17
    75.133 ns (0 allocations: 0 bytes)
  n = 18
    93.167 ns (0 allocations: 0 bytes)
  n = 19
    100.500 ns (0 allocations: 0 bytes)
  n = 20
    101.167 ns (0 allocations: 0 bytes)
  n = 21
    146.600 ns (2 allocations: 400 bytes)
Julia Version 1.14.0-DEV.1702
Commit 8bd2bea3d08 (2026-02-10 07:28 UTC)
Build Info:
  Official https://julialang.org release
Platform Info:
  OS: Linux (x86_64-linux-gnu)
  CPU: 8 × AMD Ryzen 3 5300U with Radeon Graphics
  WORD_SIZE: 64
  LLVM: libLLVM-20.1.8 (ORCJIT, znver2)
  GC: Built with stock GC
Threads: 8 default, 1 interactive, 8 GC (on 8 virtual cores)
Environment:
  JULIA_NUM_PRECOMPILE_TASKS = 2
  JULIA_PKG_PRECOMPILE_AUTO = 0

Interpretation: for lengths in 10:20, the PR avoids allocations and speeds up sorting. For other lengths there should be no change.

LilithHafner LilithHafner commented on Feb 10, 2026 14:34 UTC
Contributor

This is a bit more complicated and uses effect assertions more than it needs to.

We should make sure to match complexity with the value that it provides. In this case, we're talking about a performance improvement of sorting 10-20 element tuples, which is a fairly niche use-case.

Some specific thoughts
1. I didn't see any regression in performance when removing all compiler hints and replacing the implementation with

function _tuple_insertion_sort(tup::Tuple, ordering::Ordering)
    n = length(tup)
    mem = Memory{eltype(tup)}(undef, n)
    mem .= tup
    for i ∈ eachindex(mem)[begin:(end - 1)]  # insertion sort `mem`
        x = mem[i + 1]
        j = i
        while firstindex(mem) ≤ j
            y = mem[j]
            if !(Order.lt(ordering, x, y)::Bool)
                break
            end
            k = j + 1
            mem[k] = y
            j = j - 1
        end
        l = j + 1
        mem[l] = x
    end
    typeof(tup)(mem)
end

2. Most (but not all) of this PR's performance gains are achievable even without re-writing insertion sort, by using this implementation:
function _tuple_insertion_sort(tup::Tuple, ordering::Ordering)
    n = length(tup)
    mem = Memory{eltype(tup)}(undef, n)
    mem .= tup
    _sort!(mem, InsertionSort, ordering, (;lo=1,hi=n,scratch=nothing))
    typeof(tup)(mem)
end

For example,

julia +pr60951
  o  | Version 1.14.0-DEV.1703 (2026-02-10)
 o o | nsajko:sort-Tuple-using-Memory-while-allowing-allocation-elimination/ce06fa8aa42 (fork: 4 commits, 0 days)
julia> @benchmark sort(x) setup=(x=Tuple(rand(BigFloat, 15)))
BenchmarkTools.Trial: 10000 samples with 478 evaluations per sample.
 Range (min … max):  209.205 ns …  4.217 μs  ┊ GC (min … max): 0.00% … 88.38%
 Time  (median):     375.527 ns              ┊ GC (median):    0.00%
 Time  (mean ± σ):   383.136 ns ± 89.096 ns  ┊ GC (mean ± σ):  1.91% ±  6.70%

            ▁▂▃▅▇█▇█▇▇▇▅▄▂▁                                     
  ▂▂▂▂▃▃▄▅▇█████████████████▆▅▅▄▃▃▃▂▂▂▂▂▁▁▁▁▁▁▁▂▁▂▁▂▂▂▂▂▂▂▂▂▂▂ ▄
  209 ns          Histogram: frequency by time          772 ns <

 Memory estimate: 272 bytes, allocs estimate: 2.

julia> @eval Base.Sort function _tuple_insertion_sort(tup::Tuple, ordering::Ordering)
           n = length(tup)
           mem = Memory{eltype(tup)}(undef, n)
           mem .= tup
           _sort!(mem, InsertionSort, ordering, (;lo=1,hi=n,scratch=nothing))
           typeof(tup)(mem)
       end
_tuple_insertion_sort (generic function with 1 method)

julia> @benchmark sort(x) setup=(x=Tuple(rand(BigFloat, 15)))
BenchmarkTools.Trial: 10000 samples with 482 evaluations per sample.
 Range (min … max):  197.183 ns …   6.664 μs  ┊ GC (min … max): 0.00% … 93.84%
 Time  (median):     353.131 ns               ┊ GC (median):    0.00%
 Time  (mean ± σ):   361.821 ns ± 129.900 ns  ┊ GC (mean ± σ):  2.15% ±  5.95%

                    ▁ ▁▂▃▄▄▅▇▇▇▇▇██▇▇▆▇▆▅▅▆▅▄▂▂▁                 
  ▂▁▂▂▂▂▃▂▃▃▃▄▄▅▆▅▆▇█████████████████████████████▇▇▇▆▅▄▄▄▄▃▃▃▃▃ ▆
  197 ns           Histogram: frequency by time          487 ns <

 Memory estimate: 272 bytes, allocs estimate: 2.

nsajko nsajko commented on Feb 12, 2026 00:05 UTC
Author

Regarding @assume_effects, their purpose, as hinted at in the comment, was to enable constant folding. For example:

``julia-repl
julia> f() = sort(ntuple(identity, 10))
f (generic function with 1 method)

julia> code_typed(f)
1-element Vector{Any}:
CodeInfo(
1 ─ return (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
) => NTuple{10, Int64}
`

The above is enabled, for lengths between ten and twenty, by the @assume_effects directives. However, given how unsafe assuming the wrong effects is, I removed them from the PR. They might be reconsidered separately after this PR is merged.

Regarding @inline, yeah, your version without @inline happens to compile as desired on current master. However that is by chance, with the inlining heuristics working as intended by accident. The implementation of any (transitive) callee changing could prevent something from being inlined. As could changes in the inlining heuristics. Until aviatesk or someone finally implements interprocedural escape analysis, I feel we should force explicitly everything to be inlined. Otherwise unrelated changes in the code base would cause sort(tup) to start allocating again.

Regarding the piece of code with _sort!(mem, InsertionSort, ordering, (;lo=1,hi=n,scratch=nothing)), it is no good, causing allocation, presumably due to the mentioned lack of interprocedural escape analysis. I think maybe your benchmark is different because you define tup in the setup option to @benchmark`, while my benchmark uses interpolation. Not sure. May or may not be a BenchmarkTools bug.

nsajko nsajko commented on Feb 21, 2026 17:29 UTC
Author

I realized we can have the best of ~~both~~ all worlds via a recursive out-of-place merge sort with an iterative merge sort step and an iterative merge. Marking as draft until I update the PR.

nsajko nsajko commented on Feb 21, 2026 17:37 UTC
Author

The recursion mentioned in the previous message is not necessary to avoid allocations, however it greatly improves performance, perhaps due to unrolling.

nsajko nsajko commented on Feb 28, 2026 22:01 UTC
Author

Still want to look into some stuff before reopening the PR. Here are some results, however.

The Julia script at the end of this message:

Implements several alternative tuple sorting algorithms.

Benchmarks them for a range of tuple lengths using BenchmarkTools.jl.

At each length, several benchmarks are run, each with a different tuple value (the fixed random seed is recorded with the results).

The script, as-is, depends on Julia PR #61115.

That said, this PR (PR #60951) might not require PR #61115 after all, despite my previous statements. Still need to experiment a bit to make sure.

It should be easy to convert the script to depend on the tiny packages LightBoundsErrors.jl (registered) and NonResizableVectors.jl (not registered), instead of on PR #61115.

Outputs benchmark measurements as JSON. One such set of results is also provided at the end of this message.

The produced results may be visualized using the Vega Lite JSON view specification and the HTML file, both follow at the end of this message. For each algorithm and tuple length, these values are visualized:

interval from best-case benchmark (minimum) time to worst-case benchmark (minimum) time

count of allocated bytes

The visualization is interactively rendered. I think there is no point to giving static renders here, due to the great number of algorithms, the visualization seems difficult to intepret noninteractively. If anyone is interested, serve the HTML file and the two JSON files locally and use the visualization interactively. The interactivity mostly amounts to selecting a subset of the algorithms and adjusting the opacity of the nonselected algorithms. Another interactive feature is restricting the considered tuple length extent.

Some takeaways, from looking at the visualization:

time measurements (comparing the worst case run time among the twenty different tuple values)

For tuple lengths less than or equal to $8$, the recursive merge sort implementation by @LilithHafner, as already used on the Julia master Git branch, is the fastest.

For tuple lengths greater than or equal to $9$, the lead alternates between the insertion sort variants and the "recursive iterative merge sort" variants.

The 11 variants of "recursive iterative merge sort" are faster than the 00, 01 or 10 variants, and much faster than the "iterative merge sort" variants. After length about $21$ to $24$, depending on the variant, these seem to be consistently faster than insertion sort.

While this is not deducible from the visualization, or from the run time measurements, the 11 variants suffer from horrible compilation latency, making them not suitable as the default implementation, I feel. That said, the 00 variants are quick to compile so seem like a good choice for tuple lengths above about $24$ and below $32$.

allocation measurements

Most of the considered algorithms never allocate for the given tuple lengths.

While this is not deducible from the data provided here, all of the algorithms allocate for tuple lengths above $32$. Among the considered algorithms, the insertion sort variants allocate by far the least for tuple lengths above $32$.

The only algorithms that allocate (for tuple lengths not above $32$), are some of those that depend on Vector.

The fact that none of the Memory-based algorithms allocate suggests that the NonResizableVectors stuff may not be useful for this PR after all.

TODO: up to now I only benchmarked for the case of eltype(tup) == Float32. It might make sense to also compare the different algorithms on other element types.

<details><summary>Julia script</summary>
<p>

@eval Base function copyto_light!(dst, i::Int, src, j::Int, n::Int)
    # mostly the same as `copyto!`, except this:
    #
    # * avoids the `ccall`
    #
    # * throws `LightBoundsError` instead of `BoundsError`
    #
    # TODO: evaluate whether it is OK to just use `copyto!` instead
    @inline let
        r = 0:(n - 1)
        ri = r .+ i
        rj = r .+ j
        @boundscheck let
            checkbounds_lightboundserror(dst, ri)
            if !(issubset(rj, eachindex(src))::Bool)
                throw_lightboundserror(src, rj)
            end
        end
        @assume_effects :terminates_locally for k ∈ r
            x = @inbounds src[j + k]
            @inbounds dst[i + k] = x
        end
        dst
    end
end

@eval Base @propagate_inbounds function copyto_light!(dst, src)
    @inline let
        i = firstindex(dst)
        j = firstindex(src)
        n = length(src)
        copyto_light!(dst, i, src, j, n)
    end
end

@eval Base function indexable_to_tuple_known_length(v, ::Val{N}) where {N}
    # TODO: evaluate whether it is OK to just use `ntuple` instead
    @inline let
        function g(i::Int)
            @inline @inbounds v[i]
        end
        n = N::Int
        r = OneTo(n)
        it = Iterators.map(g, r)
        @boundscheck checkbounds_lightboundserror(v, r)
        (it...,)
    end
end

@eval Base.Sort function merge_from_to!(dst_src::NTuple{2, Any}, abc::NTuple{3, Int}, ordering::Ordering)
    @inline let
        (dst, src) = dst_src
        (a, b, c) = abc
        @boundscheck foreach((a:(c - 1), a:(b - 1), b:(c - 1))) do ran
            @inline let ran_dst = ran .+ firstindex(dst),
                        ran_src = ran .+ firstindex(src)
                Base.checkbounds_lightboundserror(dst, ran_dst)
                if !(issubset(ran_src, eachindex(src))::Bool)
                    Base.throw_lightboundserror(src, ran_src)
                end
            end
        end
        i = a
        j = b
        k_backup = a - 1
        ks = a:(c - 1)
        Base.@assume_effects :terminates_locally for k ∈ ks
            if (b ≤ i) || (c ≤ j)
                break
            end
            k_backup = k
            x = @inbounds src[begin + i]
            y = @inbounds src[begin + j]
            e = if !(Base.Order.lt(ordering, y, x)::Bool)
                i = i + 1
                x
            else
                j = j + 1
                y
            end
            @inbounds dst[begin + k] = e
        end
        k_ = firstindex(dst) + k_backup + 1
        fi = firstindex(src)
        # invariant: `(((b - i) === 0) + ((c - j) === 0)) === 1`
        @inbounds Base.copyto_light!(dst, k_, src, fi + i, b - i)
        @inbounds Base.copyto_light!(dst, k_, src, fi + j, c - j)
    end
end

@eval Base.Sort function tuple_merge_sort_step(::Type{Memory}, tup::Tuple, ordering::Ordering, width::Int) where {Memory <: AbstractVector}
    @inline let
        function throw_nonpositive_width()
            throw(ArgumentError("width not positive"))
        end
        if !(ispositive(width)::Bool)
            @noinline throw_nonpositive_width()
        end
        n = length(tup)
        elt = eltype(tup)
        T = Memory{elt}
        mem = T(undef, n)
        dw = 2 * width
        is = (1:dw:n) .- 1
        Base.@assume_effects :terminates_locally for i ∈ is
            b = min(i + width, n)
            c = min(i + dw, n)
            @inbounds merge_from_to!((mem, tup), (i, b, c), ordering)
        end
        @inbounds Base.indexable_to_tuple_known_length(mem, Val{n}())
    end
end

@eval Base.Sort function tuple_merge_sort_recursive_iterative_impl_0(::Type{Memory}, tup::Tuple, ordering::Ordering, width::Int, recursion_limit::Tuple{Vararg{Nothing}}) where {Memory <: AbstractVector}
    # bottom-up merge sort
    if recursion_limit === ()
        return tup
    end
    tup_next = tuple_merge_sort_step(Memory, tup, ordering, width)
    recursion_limit_next = Base.tail(recursion_limit)
    dw = 2 * width
    tuple_merge_sort_recursive_iterative_impl_0(Memory, tup_next, ordering, dw, recursion_limit_next)
end

@eval Base.Sort function tuple_merge_sort_recursive_iterative_impl_1(::Type{Memory}, tup::Tuple, ordering::Ordering, width::Int, recursion_limit::Tuple{Vararg{Nothing}}) where {Memory <: AbstractVector}
    # bottom-up merge sort
    @inline let
        if recursion_limit === ()
            return tup
        end
        tup_next = tuple_merge_sort_step(Memory, tup, ordering, width)
        recursion_limit_next = Base.tail(recursion_limit)
        dw = 2 * width
        tuple_merge_sort_recursive_iterative_impl_1(Memory, tup_next, ordering, dw, recursion_limit_next)
    end
end

@eval Base.Sort function tuple_merge_sort_recursive_iterative_00(::Type{Memory}, tup::Tuple, ordering::Ordering) where {Memory <: AbstractVector}
    n = length(tup)
    recursion_depth_limit = if n < 2
        0
    else
        Base.top_set_bit(n) - 1
    end
    recursion_depth_limit_tuple = ntuple(Returns(nothing), Val{recursion_depth_limit}())
    tuple_merge_sort_recursive_iterative_impl_0(Memory, tup, ordering, 1, recursion_depth_limit_tuple)
end

@eval Base.Sort function tuple_merge_sort_recursive_iterative_01(::Type{Memory}, tup::Tuple, ordering::Ordering) where {Memory <: AbstractVector}
    @inline let
        n = length(tup)
        recursion_depth_limit = if n < 2
            0
        else
            Base.top_set_bit(n) - 1
        end
        recursion_depth_limit_tuple = ntuple(Returns(nothing), Val{recursion_depth_limit}())
        tuple_merge_sort_recursive_iterative_impl_0(Memory, tup, ordering, 1, recursion_depth_limit_tuple)
    end
end

@eval Base.Sort function tuple_merge_sort_recursive_iterative_10(::Type{Memory}, tup::Tuple, ordering::Ordering) where {Memory <: AbstractVector}
    n = length(tup)
    recursion_depth_limit = if n < 2
        0
    else
        Base.top_set_bit(n) - 1
    end
    recursion_depth_limit_tuple = ntuple(Returns(nothing), Val{recursion_depth_limit}())
    tuple_merge_sort_recursive_iterative_impl_1(Memory, tup, ordering, 1, recursion_depth_limit_tuple)
end

@eval Base.Sort function tuple_merge_sort_recursive_iterative_11(::Type{Memory}, tup::Tuple, ordering::Ordering) where {Memory <: AbstractVector}
    @inline let
        n = length(tup)
        recursion_depth_limit = if n < 2
            0
        else
            Base.top_set_bit(n) - 1
        end
        recursion_depth_limit_tuple = ntuple(Returns(nothing), Val{recursion_depth_limit}())
        tuple_merge_sort_recursive_iterative_impl_1(Memory, tup, ordering, 1, recursion_depth_limit_tuple)
    end
end

@eval Base.Sort function tuple_merge_sort_iterative_0(::Type{Memory}, tup::Tuple, ordering::Ordering) where {Memory <: AbstractVector}
    # bottom-up merge sort
    n = length(tup)
    e2 = Base.Fix1(<<, 1)
    it_inf_lin = Iterators.countfrom(0)
    it_inf_exp = Iterators.map(e2, it_inf_lin)
    it_fin = Iterators.takewhile(<(n), it_inf_exp)
    Base.@assume_effects :terminates_locally for width ∈ it_fin
        tup = tuple_merge_sort_step(Memory, tup, ordering, width)
    end
    tup
end

@eval Base.Sort function tuple_merge_sort_iterative_1(::Type{Memory}, tup::Tuple, ordering::Ordering) where {Memory <: AbstractVector}
    # bottom-up merge sort
    @inline let
        n = length(tup)
        e2 = Base.Fix1(<<, 1)
        it_inf_lin = Iterators.countfrom(0)
        it_inf_exp = Iterators.map(e2, it_inf_lin)
        it_fin = Iterators.takewhile(<(n), it_inf_exp)
        Base.@assume_effects :terminates_locally for width ∈ it_fin
            tup = tuple_merge_sort_step(Memory, tup, ordering, width)
        end
        tup
    end
end

@eval Base.Sort function tuple_insertion_sort_0(::Type{Memory}, tup::Tuple, ordering::Ordering) where {Memory <: AbstractVector}
    @inline let
        n = length(tup)
        elt = eltype(tup)
        T = Memory{elt}
        mem = T(undef, n)
        Base.copyto_light!(mem, tup)
        is = eachindex(mem)[begin:(end - 1)]
        Base.@assume_effects :terminates_locally for i ∈ is  # insertion sort `mem`
            x = @inbounds mem[i + 1]
            j = i
            while firstindex(mem) ≤ j
                y = @inbounds mem[j]
                if !(Order.lt(ordering, x, y)::Bool)
                    break
                end
                k = j + 1
                @inbounds mem[k] = y
                j = j - 1
            end
            l = j + 1
            @inbounds mem[l] = x
        end
        @inbounds Base.indexable_to_tuple_known_length(mem, Val{n}())
    end
end

@eval Base.Sort function tuple_insertion_sort_1(::Type{Memory}, tup::Tuple, ordering::Ordering) where {Memory <: AbstractVector}
    @inline let
        n = length(tup)
        elt = eltype(tup)
        T = Memory{elt}
        mem = T(undef, n)
        copyto!(mem, tup)
        sort_opts = (; lo = 1, hi = n, scratch = nothing)
        @inbounds _sort!(mem, InsertionSort, ordering, sort_opts)
        @inbounds Base.indexable_to_tuple_known_length(mem, Val{n}())
    end
end

@eval Base.Sort function tuple_insertion_sort_2(::Type{Memory}, tup::Tuple, ordering::Ordering) where {Memory <: AbstractVector}
    @inline let
        n = length(tup)
        elt = eltype(tup)
        T = Memory{elt}
        mem = T(undef, n)
        mem .= tup
        sort_opts = (; lo = 1, hi = n, scratch = nothing)
        @inbounds _sort!(mem, InsertionSort, ordering, sort_opts)
        @inbounds Base.indexable_to_tuple_known_length(mem, Val{n}())
    end
end

function tuple_merge_sort_recursive(tup::Tuple)
    @inline Base.Sort._mergesort(tup, Base.Order.Forward)
end
function tuple_merge_sort_recursive_iterative_00(::Type{Memory}, tup::Tuple) where {Memory <: AbstractVector}
    @inline Base.Sort.tuple_merge_sort_recursive_iterative_00(Memory, tup, Base.Order.Forward)
end
function tuple_merge_sort_recursive_iterative_01(::Type{Memory}, tup::Tuple) where {Memory <: AbstractVector}
    @inline Base.Sort.tuple_merge_sort_recursive_iterative_01(Memory, tup, Base.Order.Forward)
end
function tuple_merge_sort_recursive_iterative_10(::Type{Memory}, tup::Tuple) where {Memory <: AbstractVector}
    @inline Base.Sort.tuple_merge_sort_recursive_iterative_10(Memory, tup, Base.Order.Forward)
end
function tuple_merge_sort_recursive_iterative_11(::Type{Memory}, tup::Tuple) where {Memory <: AbstractVector}
    @inline Base.Sort.tuple_merge_sort_recursive_iterative_11(Memory, tup, Base.Order.Forward)
end
function tuple_merge_sort_iterative_0(::Type{Memory}, tup::Tuple) where {Memory <: AbstractVector}
    @inline Base.Sort.tuple_merge_sort_iterative_0(Memory, tup, Base.Order.Forward)
end
function tuple_merge_sort_iterative_1(::Type{Memory}, tup::Tuple) where {Memory <: AbstractVector}
    @inline Base.Sort.tuple_merge_sort_iterative_1(Memory, tup, Base.Order.Forward)
end
function tuple_insertion_sort_0(::Type{Memory}, tup::Tuple) where {Memory <: AbstractVector}
    @inline Base.Sort.tuple_insertion_sort_0(Memory, tup, Base.Order.Forward)
end
function tuple_insertion_sort_1(::Type{Memory}, tup::Tuple) where {Memory <: AbstractVector}
    @inline Base.Sort.tuple_insertion_sort_1(Memory, tup, Base.Order.Forward)
end
function tuple_insertion_sort_2(::Type{Memory}, tup::Tuple) where {Memory <: AbstractVector}
    @inline Base.Sort.tuple_insertion_sort_2(Memory, tup, Base.Order.Forward)
end

using Random: Xoshiro
using BenchmarkTools: @benchmarkable

function random_elements(::Type{T}, length::Int, prng_seed) where {T}
    prng = Xoshiro(prng_seed)
    function f(_::Int)
        rand(prng, T)
    end
    r = 1:length
    Iterators.map(f, r)
end

function random_tuple(::Type{T}, length::Int, prng_seed) where {T}
    it = random_elements(T, length, prng_seed)
    (it...,)
end

function force_gc(n::Int, full::Bool)
    for _ ∈ 1:n
        GC.gc(full)
    end
end

function with_disabled_gc_more_oom_danger(func)
    GC.enable(false)
    try
        func()
    finally
        GC.enable(true)
    end
end

function with_forced_gc_before_and_after(func, n::Int)
    full = true
    force_gc(n, full)
    try
        func()
    finally
        force_gc(n, full)
    end
end

function with_disabled_gc(func::Func, n::Int) where {Func}
    f = Base.Fix1(with_disabled_gc_more_oom_danger, func)
    with_forced_gc_before_and_after(f, n)
end

function benchmarktools_estimate(trial)
    estimate = minimum(trial)
    (;
        minimum_time = estimate.time,
        allocated_byte_count = estimate.memory,
        allocation_count = estimate.allocs,
    )
end

function measure_runtime_performance(prng_seed::Integer, name::AbstractString, func, length::Int)
    tuple = random_tuple(Float32, length, prng_seed)
    @eval ($func)($tuple)
    trial = with_disabled_gc(2) do
        run(@benchmarkable ($func)($tuple) evals=evals samples=samples seconds=Inf gctrial=false)
    end
    measurement = benchmarktools_estimate(trial)
    (prng_seed, name, length, measurement)
end

function show_results_as_json_table_row(
    io::IO,
    prng_seed::Integer,
    name::AbstractString,
    length::Int,
    (; minimum_time, allocated_byte_count, allocation_count),
)
    pr = Base.Fix1(print, io)
    prng_seed_int = Int64(prng_seed)::Int64
    members = (
        lazy"\"BenchmarkTools parameter evals\": $evals",
        lazy"\"BenchmarkTools parameter samples\": $samples",
        lazy"\"tuple length\": $length",
        lazy"\"algorithm\": \"$name\"",
        lazy"\"PRNG seed\": $prng_seed_int",
        lazy"\"measured allocated bytes\": $allocated_byte_count",
        lazy"\"measured allocations\": $allocation_count",
        lazy"\"minimum measured time (ns)\": $minimum_time",
    )
    pr("    { ")
    try
        fir_res = Iterators.peel(members)
        if fir_res === nothing
            return
        end
        let (fir, res) = fir_res
            pr(fir)
            for e ∈ res
                pr(", ")
                pr(e)
            end
        end
    finally
        pr(" }")
        flush(io)
    end
    nothing
end

function fix1_type(f::F, ::Type{T}) where {F, T}
    function closure(x)
        @inline f(T, x)
    end
end

function splat_argument_1(a, bs...)
    (a..., bs...)
end
function splat_argument_2(a, b, cs...)
    (a, b..., cs...)
end

function nice_type_name(type::Type)
    if type === Base.MemoryVector
        "MemoryVector"
    elseif type === Base.MemoryRefVectorImm
        "MemoryRefVectorImm"
    elseif type === Base.MemoryRefVectorMut
        "MemoryRefVectorMut"
    else
        string(type)
    end
end

function todo_how_to_name_this(name::AbstractString, func, type::Type)
    type_name = nice_type_name(type)
    l = lazy"$name: $type_name"
    f = fix1_type(func, type)
    (l, f)
end

const root_prng_seed = 0xfe03600518d05674acc49e4c4308a629

function iterator_funcs_without_seeds(lengths)
    vector_types = (
        Vector,
        Memory,
        Base.MemoryVector,
        Base.MemoryRefVectorImm,
        Base.MemoryRefVectorMut,
    )
    __funcs_without_type = (
        ("recursive iterative merge sort 00", tuple_merge_sort_recursive_iterative_00),
        ("recursive iterative merge sort 01", tuple_merge_sort_recursive_iterative_01),
        ("recursive iterative merge sort 10", tuple_merge_sort_recursive_iterative_10),
        ("recursive iterative merge sort 11", tuple_merge_sort_recursive_iterative_11),
        ("iterative merge sort 0", tuple_merge_sort_iterative_0),
        ("iterative merge sort 1", tuple_merge_sort_iterative_1),
        ("insertion sort 0", tuple_insertion_sort_0),
        ("insertion sort 1", tuple_insertion_sort_1),
        ("insertion sort 2", tuple_insertion_sort_2),
    )
    __funcs_with_type = Iterators.product(__funcs_without_type, vector_types)
    _funcs = Iterators.map(splat(todo_how_to_name_this) ∘ splat(splat_argument_1), __funcs_with_type)
    funcs = (Iterators.flatten ∘ tuple)(
        (
            ("recursive merge sort", tuple_merge_sort_recursive),
        ),
        _funcs,
    )
    it_needs_splatting = Iterators.product(funcs, lengths)
    Iterators.map(splat(splat_argument_1), it_needs_splatting)
end

function iterator_funcs_with_seeds(seed_count::Int, lengths)
    prng_seeds_iterator = random_elements(UInt32, seed_count, root_prng_seed)
    prng_seeds_vector = collect(UInt32, prng_seeds_iterator)
    prng_seeds_vector = sort!(prng_seeds_vector)
    prng_seeds = (prng_seeds_vector...,)
    it = iterator_funcs_without_seeds(lengths)
    it_needs_splatting = Iterators.product(prng_seeds, it)
    Iterators.map(splat(splat_argument_2), it_needs_splatting)
end

function iterator_funcs_without_seeds_filtered(lengths, pattern)
    it = iterator_funcs_without_seeds(lengths)
    f = contains(pattern) ∘ Base.Fix2(getindex, 1)
    Iterators.filter(f, it)
end

function measure_and_report_as_json(io::IO, seed_count::Int)
    pr = Base.Fix1(print, io)
    f = (
        splat(Base.Fix1(show_results_as_json_table_row, io)) ∘
        splat(measure_runtime_performance)
    )
    it = iterator_funcs_with_seeds(seed_count, min_n:max_n)
    pr("[\n")
    try
        fir_res = Iterators.peel(it)
        if fir_res === nothing
            return
        end
        let (fir, res) = fir_res
            f(fir)
            for e ∈ res
                pr(",\n")
                f(e)
            end
            pr('\n')
        end
    finally
        pr("]\n")
        flush(io)
    end
    nothing
end

function command_measure_runtime(args)
    samples = parse(Int, args[1])
    evals = parse(Int, args[2])
    seed_count = parse(Int, args[3])
    min_n = parse(Int, args[4])
    max_n = parse(Int, args[5])
    print(
        stderr,
        "samples = $samples\n",
        "evals = $evals\n",
        "seed_count = $seed_count\n",
        "min_n = $min_n\n",
        "max_n = $max_n\n",
    )
    @eval const samples = $samples
    @eval const evals = $evals
    @eval const min_n = $min_n
    @eval const max_n = $max_n
    @invokelatest measure_and_report_as_json(stdout, seed_count)
end

function command_measure_latency(args)
    min_n = parse(Int, args[1])
    max_n = parse(Int, args[2])
    pattern = Regex(args[3], "s")
    print(
        stderr,
        "min_n = $min_n\n",
        "max_n = $max_n\n",
        "pattern = $pattern\n",
    )
    it_funcs_filtered = iterator_funcs_without_seeds_filtered(min_n:max_n, pattern)
    for (name, func, length) ∈ it_funcs_filtered
        @show name
        @show length
        tup = random_tuple(Float32, length, root_prng_seed)
        @eval @time @eval ($func)($tup)
    end
end

function (@main)(args)
    if isempty(args)
        return
    end
    (command, r...) = args
    if command == "measure runtime"
        @noinline command_measure_runtime(r)
    elseif command == "measure latency"
        @noinline command_measure_latency(r)
    end
    nothing
end

</p>
</details>

<details><summary>the HTML file for the Vega Lite visualization</summary>
<p>

<!DOCTYPE html>
<html>

<head>
  <style>
    vega-chart.vega-embed {
      width: 100%;
      display: flex;
    }

    vega-chart.vega-embed details,
    vega-chart.vega-embed details summary {
      position: relative;
    }
  </style>
  <meta charset="UTF-8">
  <title>Chart</title>
  <script src="https://cdn.jsdelivr.net/npm/vega@6"></script>
  <script src="https://cdn.jsdelivr.net/npm/vega-lite@6"></script>
  <script src="https://cdn.jsdelivr.net/npm/vega-embed@7"></script>
</head>

<body>
  <div id="vega-chart"></div>
  <script type="text/javascript">
    {
      const opts = { "renderer": "svg" }
      fetch(
        '/vega-lite/vl.json'
      ).then(
        (res) => res.json()
      ).then(
        (spec) => vegaEmbed('#vega-chart', spec, opts).catch(console.error)
      );
    }
  </script>
</body>

</html>

</p>
</details>

<details><summary>Vega Lite JSON view spec, referred to as /vega-lite/vl.json from the HTML file</summary>
<p>

{
    "$schema": "https://vega.github.io/schema/vega-lite/v6.json",
    "title": "Performance comparison between several tuple sort variants",
    "data": {
        "url": "http://localhost:8000/data/measured-runtime.json"
    },
    "params": [
        {
            "name": "minimum_considered_tuple_length",
            "value": 0,
            "bind": {
                "input": "range",
                "min": 0,
                "max": 100,
                "step": 1
            }
        },
        {
            "name": "maximum_considered_tuple_length",
            "value": 50,
            "bind": {
                "input": "range",
                "min": 0,
                "max": 100,
                "step": 1
            }
        },
        {
            "name": "unselected_algorithm_opacity",
            "value": 0.125,
            "bind": {
                "input": "range",
                "min": 0,
                "max": 0.25
            }
        },
        {
            "name": "selected_algorithm",
            "select": {
                "type": "point",
                "fields": [
                    "algorithm"
                ]
            },
            "bind": "legend"
        }
    ],
    "transform": [
        {
            "filter": {
                "field": "tuple length",
                "gte": {
                    "expr": "minimum_considered_tuple_length"
                }
            }
        },
        {
            "filter": {
                "field": "tuple length",
                "lte": {
                    "expr": "maximum_considered_tuple_length"
                }
            }
        },
        {
            "joinaggregate": [
                {
                    "op": "min",
                    "field": "minimum measured time (ns)",
                    "as": "best-case minimum measured time"
                }
            ],
            "groupby": [
                "algorithm",
                "tuple length"
            ]
        },
        {
            "joinaggregate": [
                {
                    "op": "max",
                    "field": "minimum measured time (ns)",
                    "as": "worst-case minimum measured time"
                }
            ],
            "groupby": [
                "algorithm",
                "tuple length"
            ]
        }
    ],
    "resolve": {
        "scale": {
            "x": "shared"
        }
    },
    "vconcat": [
        {
            "width": 1200,
            "height": 600,
            "mark": "area",
            "encoding": {
                "color": {
                    "field": "algorithm",
                    "type": "nominal",
                    "legend": {
                        "labelLimit": 9999999,
                        "symbolLimit": 9999999
                    }
                },
                "opacity": {
                    "value": {
                        "expr": "unselected_algorithm_opacity"
                    },
                    "condition": {
                        "param": "selected_algorithm",
                        "value": 1,
                        "empty": false
                    }
                },
                "x": {
                    "field": "tuple length",
                    "type": "quantitative"
                },
                "y": {
                    "title": "minimum measured time, interval from best- to worst-case (ns)",
                    "field": "best-case minimum measured time",
                    "type": "quantitative"
                },
                "y2": {
                    "field": "worst-case minimum measured time"
                }
            }
        },
        {
            "width": 1200,
            "height": 100,
            "mark": "line",
            "encoding": {
                "color": {
                    "field": "algorithm",
                    "type": "nominal",
                    "legend": {
                        "labelLimit": 9999999,
                        "symbolLimit": 9999999
                    }
                },
                "opacity": {
                    "value": {
                        "expr": "unselected_algorithm_opacity"
                    },
                    "condition": {
                        "param": "selected_algorithm",
                        "value": 1,
                        "empty": false
                    }
                },
                "x": {
                    "field": "tuple length",
                    "type": "quantitative"
                },
                "y": {
                    "field": "measured allocated bytes",
                    "type": "quantitative"
                }
            }
        }
    ]
}

</p>
</details>

Benchmarking measurements, referred to as data/measured-runtime.json from the Vega Lite view specification:

measured-runtime.json

Reviewers
Assignees
nsajko nsajko
Labels
risk: low confidence: 81.1% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 48.5% (MEDIUM) · Higher = larger blast radius
48.5%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 81.1% · Lower = rushed or shallow review
81.1%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 9.2% · Safe to merge
9.2%