Monday, January 7, 2013

Thought on Preview of Immutable Collections

Did you ever think of having immutable collection in your .net code - a collection that is really thread-safe and gurantees no other thread will ever change it while one thread is sort of reading it? I thought ReadOnlyCollection<T> and ConcurrentBag<T> were to my rescue, but surprisingly they aren’t.

Early this morning while having my regular cup of coffee “keep me updated” time, I came across this news "Preview of Immutable Collections Released on NuGet". Well apparently this immutable collection is something to think about, and not surprisingly Microsoft is already on it. I’m assuming that you are already familiar with the “immutable” concept in .net. If not you can take string as an example. String is one of a kind immutable collection of char, which means whenever you add or remove a character from a string object you get a new one. The state of immutable objects cannot be changed. When you do so, you get a new object instead. The older one is still intact. For more explaination you can always refer to wiki.

Immutable collections behave in a similar way. If you have grabbed the concept of immutability(getting a different one after changing the original), then you surely must be thinking that this thing is going to cost you some memory and for a huge list- millions of byte. On the contrary, immutable list are stored as immutable binary tree structures instead of flat arrays. This has a huge benefit as the new list returned after changes share the same memory space with the original immutable list.

So what if you want your list to be mutable for an instance, make the necessary changes-addition and removal of the list items and then return back the immutable list once again. This is going to save you some overhead. Bingo....Immutable lists do have a method called ToBuilder() that gives you it’s corresponding Builder class similar to StringBuilder. You can then mutate the collection, and use ToImmutable() function of the builder to return Immutable list again. The concept is very much similar to String and StringBuilder, so won’t be that hard to get used to it.

Immutable collection seem to be worth trying out. Haven’t done any benchmarking test on it yet, but hopefully somebody will come up with it one day. :) . Do check it out, but make sure you read this post by Eric Lippert as well.

No comments:

Post a Comment