is it efficient approach to use different collection types dynamicaly based on the predictable items count?
It can be depending on what you mean by "efficiency" (MS offers HybridDictionary
class for that, though unfortunately it is non generic). But irrespective of that its mostly a bad choice. I will explain both.
From an efficiency standpoint:
Addition will be always faster in a List<T>
, since a HashSet<T>
will have to precompute hash code and store it. Even though removal and lookup will be faster with a HashSet<T>
as size grows up, addition to the end is where List<T>
wins. You will have to decide which is more important to you.
HashSet<T>
will come up with a memory overhead compared to List<T>
. See this for some illustration.
But however, from a usability standpoint it need not make sense. A HashSet<T>
is a set, unlike a bag which List<T>
is. They are very different, and their uses are very different. For:
HashSet<T>
cannot have duplicates.
HashSet<T>
will not care about any order.
So when you return a hybrid ICollection<T>
, your requirement goes like this: "It doesn't matter whether duplicates can be added or not. Sometimes let it be added, sometimes not. Of course iteration order is not important anyway" - very rarely useful.
Good q, and +1.