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?
Let's take a look at how each of those is implemented.
First off, the
ToImmutableList()extension method involves first trying to cast toImmutableList<T>, and then falling back toImmutableList<T>.Empty.AddRange()otherwise.ImmutableList.Create()andImmutableList.CreateRange()also callImmutableList<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 usesImmutableList<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.