Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ImmutableList<T>'s enumerator so much slower compared to List<T>

I have a piece of code that iterates over a small list frequently. Given that the list never changes during runtime, I replaced the implementation with ImmutableList<T>. Looking at a performance trace by dotTrace, this performs much worse than a normal List<T>:

dotTrace Result (List<T> on left, ImmutableList<T> on right)

Why is this occurring and is there a workaround?

like image 282
JohnD Avatar asked Feb 20 '15 04:02

JohnD


People also ask

Why use immutable list?

The common use case for the immutable methods is a collection that is initialized from known values, and that never changes. Also consider using these methods if your data changes infrequently. For optimal performance, the immutable collections store a data set that never changes.

Is immutable list thread safe C#?

This type is immutable, so it is always thread-safe.

What is ImmutableList C#?

In software development, an immutable object is one that once created, can't change.

Is a collection of objects which ordered and immutable?

A set is an ordered collection of objects.


1 Answers

Unlike List<T> which wraps around an array that is resized as needed, ImmutableList<T> internally uses an immutable AVL tree (see Channel9 video discussing this).

So how can I still achieve this using Immutable Collections?

Use ImmutableArray<T>.

Quoting from a .NET Framework blog post about Immutable Collections

Reasons to use immutable array:

  • Updating the data is rare or the number of elements is quite small (<16)
  • you need to be able to iterate over the data in performance critical sections
  • you have many instances of immutable collections and you can’t afford keeping the data in trees

Reasons to stick with immutable list:

  • Updating the data is common or the number of elements isn’t expected to be small
  • Updating the collection is more performance critical than iterating the contents
like image 64
JohnD Avatar answered Sep 28 '22 12:09

JohnD