Benchmark FrozenColletion + Database Read

Author:

It came to my knowledge about the FrozenCollection (System.Collections.Frozen) on .NET 8. This collection is something we need to get attention on.

In this article, I would like to show the results I got when running benchmark tests between collections (including the FrozenCollection).

What is this FrozenCollection

Extracted from here.

This collection has 2 methods:

FrozenDictionary -> Provides an immutable, read-only dictionary optimized for fast lookup and enumeration.

FrozenSet -> Provides an immutable, read-only set optimized for fast lookup and enumeration.

So basically this collection is the fastest when it comes about lookup or search. I’m going show results that states it.

What’s being tested ?

I’m testing 3 collections conversion methods:

  • ToDictionary
  • ToHasSet
  • ToFrozenDictionary
  • ToFrozenSet

I’m testing on 3 ways

  • Getting Entities from Database and then converting to each collection.
  • Getting Entities from Database and casting to specific type <T>
  • Reading from static existing list.

Tests & Results

  • This tests reads data from database at the Setup test and converting to the respective collection and search for a key.
  • This test is just reading from an existing created list and it is performing search using ConstainsKey. Note how fast it is.
  • This test just shows the time it takes to convert a List<> into a respective collection.
  • This test shows the time it takes to get a list from the cache and converting to collection

Conclusion

There’s a cost to converting a List into a frozen collection (FrozenSet or FronzeDictionary), down side of having to do this converting takes ~ 50%-60% more time, however once you have the list converted, the search for elements will be the fasted among the other collections.

The reason for this cost is because it guarantee immutability and manages its engine to create a great performance search as well being ThreadSafe.

I recommend to use Frozen Collections for operations that will don’t need to go to the database very often, another approach would be to have this collection on memory.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *