FrozenDictionary
: AFrozenDictionary
represents a read-only dictionary that’s optimized for quick searches. You should use this assortment when the gathering must be created as soon as and browse ceaselessly.FrozenSet
: AFrozenSet
represents a read-only immutable set optimized for quick searches and enumeration. Like aFrozenDictionary
, you can not alter this assortment after creation.
As a result of each FrozenSet
and FrozenDictionary
are read-only collections, you can not add, change, or take away objects in these collections.
Create frozen collections in C#
The next code snippet exhibits how one can create a FrozenSet
from a HashSet
occasion, populate it with pattern information, after which seek for an merchandise inside it. Recall {that a} HashSet
is an unordered assortment of distinctive components that helps set operations (union, intersection, and many others.) and makes use of a hash desk for storage.
var hashSet = new HashSet { "A", "B", "C", "D", "E" };
var frozenSet = hashSet.ToFrozenSet();
bool isFound = frozenSet.TryGetValue("A", out _);
Within the previous code snippet, the ToFrozenSet()
technique is used to transform a HashSet
occasion to a FrozenSet
occasion. The strategy TryGetValue()
will return true
on this instance as a result of the information looked for is current within the assortment.
The next code exhibits how one can create a FrozenDictionary
, retailer information in it, and seek for a selected key within the assortment.
var dictionary = new Dictionary
{
{ 1, "A" },{ 2, "B" },{ 3, "C" },{ 4, "D" },{ 5, "E" }
};
var frozenDictionary = dictionary.ToFrozenDictionary();
bool isFound = dictionary.TryGetValue(7, out _);
When the above code is executed, the TryGetValue
technique will return false
as a result of the important thing 7
shouldn’t be accessible within the assortment.
Benchmarking efficiency of frozen collections in .NET Core
Allow us to now benchmark the efficiency of a frozen assortment, particularly a FrozenSet
, in opposition to different assortment sorts utilizing the BenchmarkDotNet library. For comparability, we’ll use a Checklist
, a HashSet
, and an ImmutableHashSet
.
Recall {that a} Checklist
is a mutable, strongly-typed, dynamically-sized, ordered assortment of components (even duplicates), and {that a} HashSet
is a mutable, array-based assortment of distinctive components that’s optimized for quick look-ups. Observe that the time complexity for looking out an merchandise in a HashSet
is O(1), in comparison with a time complexity of O(n) for a Checklist
(the place n is the variety of components within the assortment). Clearly, a HashSet
is helpful in circumstances the place fast entry is important. On the draw back, a HashSet
consumes extra reminiscence than a Checklist
and can’t embrace duplicate components. You need to use a Checklist
if you wish to retailer an ordered assortment of things (presumably duplicates) and the place useful resource consumption is a constraint.