Reputation: 21767
I heard about that type casting
is slow. I had thought comparison
is fast, but...
It seems IComparable.CompareTo(object y)
has to use the cast
, which would make x > y
at least as slow as y as MyClass
if not slower if there is no IComparable<T>
available.
So, am I right to say that:
It is always better to implement IComparable<T>
than IComparable
because then we don't have to type cast?
Is boxing
much slower than type casting between 2 reference types?
Upvotes: 0
Views: 178
Reputation: 437734
From a performance standpoint it's always better to implement the generic versions of these interfaces because it's a guarantee that you will avoid the boxing of value types, which is the #1 performance killer in this type of scenario.
It is also the case that the generic versions will also not need to make runtime type checks, but the performance hit from these checks is very smaller than that from boxing and will be much harder to notice in practice.
Seeing as there's nothing you lose by implementing IComparable<T>
then the conclusion it's clear: you should always do it, as there's nothing to lose and potentially quite a bit to gain.
Upvotes: 1
Reputation: 13990
It's always better implement generics. Not only for performance, also because you get compile time checking.
Upvotes: 0