← All articles

Optimizing .NET: Day 1

From December 1 through Christmas Eve, I’ll cover one .NET runtime-library optimization a day.

SortedSet.CopyTo()#

C#
var set = new SortedSet<int> { 7, 3, 5 };
var destination = new int[set.Count];

set.CopyTo(destination);
// destination is [3, 5, 7]

SortedSet's CopyTo() uses a heap-backed traversal stack and a capturing predicate. The patch recurses into left subtrees, writes each item directly to the destination, and loops through right subtrees.

C#
private static int CopyInOrder(Node? node, T[] array, int index, int end)
{
    while (node != null)
    {
        if (node.Left is Node left)
        {
            index = CopyInOrder(left, array, index, end);
            if (index == end)
            {
                break;
            }
        }

        array[index++] = node.Item;
        if (index == end)
        {
            break;
        }

        node = node.Right;
    }

    return index;
}

Stock and patched .NET 11 each passed 15,394 SortedSet tests, including the new partial-copy test. Both skipped 11 serialization tests.

Benchmark#

Copy128 copies a 128-element SortedSet<int> into a reused array. Each operation copies 512 B.

Metric Before After Change
Mean latency (ns/op) 481.82 144.50 70.0% lower
Managed allocation (B/op) 256 0 100.0% lower
Throughput (MB/s) 1,063 3,543 233.4% higher

Results

Method Job Mean Error StdDev Ratio Allocated Alloc Ratio
Copy8 stock 50.055 ns 2.2147 ns 1.6013 ns 1.00 192 B 1.00
Copy8 patched 7.753 ns 0.3695 ns 0.2672 ns 0.16 - 0.00
Copy128 stock 481.822 ns 48.0908 ns 37.5461 ns 1.01 256 B 1.00
Copy128 patched 144.499 ns 7.4274 ns 5.7989 ns 0.30 - 0.00
Copy4096 stock 13,553.965 ns 1,177.2689 ns 919.1341 ns 1.00 336 B 1.00
Copy4096 patched 5,260.886 ns 297.0077 ns 214.7560 ns 0.39 - 0.00

Reproduce#

With the .NET 11 SDK installed, run this from the extracted benchmark directory.

Shell
dotnet run -c Release

The benchmark loads the bundled stock and patched libraries. Both were built from dotnet/runtime commit deae2e32bf0e018e09d64597b7c59b62b73bb3ce.

Download the patch with tests | Download the benchmark