Collection Performance: Creating Immutable Sorted Collections

Updated January 2024

Two immutable sorted collections are available: ImmutableSortedDictionary and ImmutableSortedSet<>. Below is an example illustrating how to construct an immutable sorted collection using a builder.

var builder = ImmutableSortedSet.CreateBuilder<Person>();

foreach (var person in people)
{
    _ = builder.Add(person);
}

var collection = builder.ToImmutable();

You also have the option to utilize CreateRange().

var collection = ImmutableSortedDictionary.CreateRange(personDictionary);

Benchmark Results

Here are the performance results. As evident, the ImmutableSortedDictionary<,> consistently shows lower performance compared to the ImmutableSortedSet<> in both scenarios. Furthermore, using CreateRange() proves to be more performant than employing CreateBuilder() with foreach().

I’d like to emphasize that employing a regular List<> with the Sort() method tends to be more efficient than opting for an immutable sorted collection.

Allocations: ImmutableSortedDictionary<,>: 1,008 – 114,801 bytes. ImmutableSortedSet<>: 856 – 98,392  bytes. ImmutableList<> + Sort(): 1,808 – 213,137 bytes.

Allocations: ImmurableSortedDictionary<,>: 2,536 – 262,745 bytes. ImmutableSortedSet<>: 1,008 – 114, 800 bytes.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.