Search code examples
c#immutable-collections

Differences between ways of creating ImmutableList


What is the differences between ways of creating ImmutableList?

List<int> numbers = new List<int>(){0, 1, 2, 3};
ImmutableList<int> immutableList = numbers.ToImmutableList();

ImmutableList<int> immutableList = ImmutableList.Create<int>(0, 1, 2, 3);

ImmutableList<int> immutableList = ImmutableList.CreateRange<int>(new List<int>() { 0, 1, 2, 3 });

ImmutableList<int>.Builder builder = ImmutableList.CreateBuilder<int>();
builder.AddRange(new List<int>() { 0, 1, 2, 3 });
ImmutableList<int> immutableList = builder.ToImmutableList();

Which is the faster and usabel?


Solution

  • Let's take a look at how each of those is implemented.

    First off, the ToImmutableList() extension method involves first trying to cast to ImmutableList<T>, and then falling back to ImmutableList<T>.Empty.AddRange() otherwise. ImmutableList.Create() and ImmutableList.CreateRange() also call ImmutableList<T>.Empty.AddRange().

    Finally, the builder is the only one that has some key difference, although you're using it wrong: you should be using ToImmutable(), because it involves doing fewer unecessary copies. ToImmutableList() just uses the above extension method, and therefore also uses ImmutableList<T>.Empty.AddRange().

    Really, if you're building a possibly large immutable list as you go, you should use a builder, and then freeze it with ToImmutable() when you're done modifying it. Otherwise, all the other methods are functionally identical, so pick whichever is clearest to you.