Repository navigation
Description
Description
ImmutableList<T>.Reverse() and ImmutableList<T>.Builder.Reverse() take O(n log n) time. A copy to an array, Array.Reverse and ImmutableList.Create give the same list 6 to 8 times faster from 10 000 elements on, with about the same allocation.
var list = ImmutableList.CreateRange(Enumerable.Range(0, 100_000));
var reversed = list.Reverse(); // about 32 ms
var array = new int[list.Count];
list.CopyTo(array);
Array.Reverse(array);
var rebuilt = ImmutableList.Create<int>(array.AsSpan()); // about 5 ms, the same elementsConfiguration
BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300), AMD Ryzen AI MAX+ 395 (16 cores), .NET 10.0.13, X64 RyuJIT x86-64-v4, --job short.
Regression?
Not that I know of: the current main uses the same algorithm.
Data
[MemoryDiagnoser]
public class ReverseBenchmarks
{
private ImmutableList<int> list = ImmutableList<int>.Empty;
[Params(100, 10_000, 100_000)]
public int Count { get; set; }
[GlobalSetup]
public void Setup() => list = ImmutableList.CreateRange(Enumerable.Range(0, Count));
[Benchmark(Baseline = true)]
public ImmutableList<int> Reverse() => list.Reverse();
[Benchmark]
public ImmutableList<int> CopyReverseCreate()
{
var array = new int[list.Count];
list.CopyTo(array);
Array.Reverse(array);
return ImmutableList.Create<int>(array.AsSpan());
}
}| Method | Count | Mean | Ratio | Allocated |
|---|---|---|---|---|
| Reverse | 100 | 7.650 us | 1.00 | 4.71 KB |
| CopyReverseCreate | 100 | 3.443 us | 0.45 | 5.13 KB |
| Reverse | 10000 | 2,725.800 us | 1.00 | 468.77 KB |
| CopyReverseCreate | 10000 | 323.030 us | 0.12 | 507.86 KB |
| Reverse | 100000 | 32,363.922 us | 1.00 | 4687.52 KB |
| CopyReverseCreate | 100000 | 5,116.358 us | 0.16 | 5078.2 KB |
Analysis
ImmutableList<T>.Node.Reverse(int index, int count) (ImmutableList_1.Node.cs) swaps the ends one pair at a time:
T a = result.ItemRef(start);
T b = result.ItemRef(end);
result = result
.ReplaceAt(end, a)
.ReplaceAt(start, b);Every ItemRef and ReplaceAt descends the tree from the root, so a reverse of n elements costs O(n log n) time. The allocation stays at about one node per element. Node.Reverse() and Builder.Reverse() both call Reverse(0, Count).
The reverse of the whole tree can be its mirror: every node keeps its key and takes its children reversed and swapped. That is O(n) time with one new node per element, and the result stays balanced, because the mirror keeps every height. A sketch:
internal Node Reverse() => this.IsEmpty ? this : new Node(_key, _right!.Reverse(), _left!.Reverse(), frozen: true);Reverse(int index, int count) could take this path when the range is the whole list and keep the loop for a part of it.
Activity
dotnet-policy-service commentedon Oct 18, 2026
Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.
Make whole-list ImmutableList<T>.Reverse() O(n) (#136063)
docs: note at `rev` of `IndexedList` and its builder that .NET 12 mak…