I have never written a stateful IComparer<T>
with a default constructor. All standard library implementations which I've checked in Reflector are stateless as well. Therefore, I'd like to assume that I can freely cache IComparer<T>
like this:
PriorityQueue<TPriority, TComparer> where TComparer : IComparer<TPriority>, new()
{
private static TComparer _comparer = new TComparer();
public PriorityQueue() {...}
...
}
instead of
PriorityQueue<TPriority>
{
private IComparer<TPriority> _comparer;
public PriorityQueue(IComparer<TPriority> comparer) {
_comparer = comparer;
...
}
...
}
So here is the question: have you ever written/seen an IComparer<T>
for which this would break down? If yes, how common is it?
EDIT: The reason I really don't want the overhead of the second version in this case is that the data structure is persistent. It is implemented as a tree where nodes have no parent/root reference. So it wouldn't be one reference to comparer per queue, but one reference to comparer per node! My original design was just to use IComparable<T>
and recommend writing a wrapper struct for custom comparisons.