Jump to content


Photo
- - - - -

The Iequatable<T> Interface


  • Please log in to reply
2 replies to this topic

#1 AlCarn

AlCarn

    New Member

  • Members
  • Pip
  • 2 posts

Posted 15 February 2012 - 12:34 PM

On page 264 while discussing IEquatable<T>, the following line appears:

"If we remove the generic constraint, the class would still compile, but a.Equals(B) would bind to the slower object.Equals (slower assuming T was a value type)."

Is this true? Doesn't the constraint just limit the types you can use with the generic to types that implement IEquatable<T>? If you remove the constraint, you could create the generic with either types that implement the interface or do not and wouldn't the binding just depend on what type you used?

Al

#2 JoeAlbahari

JoeAlbahari

    Super Veteran Member

  • Members
  • PipPipPipPipPipPipPipPipPipPipPip
  • 529 posts
  • Gender:Male
  • Location:Perth, Australia

Posted 15 February 2012 - 06:35 PM

Unless you use the dynamic keyword, binding decisions in C# are made at compile-time rather than runtime.

The situation with a type constraint is no different to what happens in the following two methods:

void Foo1 (object x) { x.Equals (x); }

void Foo2<T> (IEquatable<T> x) { x.Equals(x); }

The call to Equals in Foo1 binds to object's Equals method, whereas the Equals in Foo2 binds to IEquatable<T>'s Equals method. The latter avoids boxing overhead and so is faster.

Bear in mind, though, that avoiding boxing is a micro-optimization. It's worth doing if either:
(1) It can be done effortlessly (IEquatable<T> might be included in this category)
(2) You're trying to make code that's called millions of times in a loop run faster

Joe

Edited by JoeAlbahari, 15 February 2012 - 06:35 PM.


#3 AlCarn

AlCarn

    New Member

  • Members
  • Pip
  • 2 posts

Posted 16 February 2012 - 04:07 AM

Makes sense. Thanks.

Unless you use the dynamic keyword, binding decisions in C# are made at compile-time rather than runtime.

The situation with a type constraint is no different to what happens in the following two methods:

void Foo1 (object x) { x.Equals (x); }

void Foo2<T> (IEquatable<T> x) { x.Equals(x); }

The call to Equals in Foo1 binds to object's Equals method, whereas the Equals in Foo2 binds to IEquatable<T>'s Equals method. The latter avoids boxing overhead and so is faster.

Bear in mind, though, that avoiding boxing is a micro-optimization. It's worth doing if either:
(1) It can be done effortlessly (IEquatable<T> might be included in this category)
(2) You're trying to make code that's called millions of times in a loop run faster

Joe






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users