GetHashCode() <> pt2.GetHashCode() Then
Return False
Else
Return Object.Equals(pt1, pt2)
End If
End Operator
Public Shared Operator <>(ByVal pt1 As Point, ByVal pt2 As Point) As Boolean
If pt1.GetHashCode() <> pt2.GetHashCode() Then
Return True
Else
Return Not Object.Equals(pt1, pt2)
End If
End Operator
End Class
CHAPTER 14 n VB 2008 BEST PRACTICES 351
In this example, as long as the precomputed hash is sufficiently unique, the overloaded
operators will execute quickly in some cases. In the worst case, one more compare between
two integers??”the hash values??”is executed along with the function calls to acquire them. If
the call to Equals() is expensive, then this optimization will return some gains on a lot of the
comparisons. If the call to Equals() is not expensive, then this technique could add overhead
and make the code less efficient. It??™s best to apply optimizations after a profiler has pointed
you in this direction and if you??™re sure it will help.
Object.GetHashCode() exists because the developers of the standard library felt it would
be convenient to be able to use any object as a key to a hash table. The fact is, not all objects
are good candidates for hash keys. Usually, it??™s best to use immutable types as hash keys.
Pages:
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574