2

What are the implications of using a class through an interface as opposed to using the class directly?

For example when mutating a list of integers through the IList<Int32> interface as opposed to using the List<Int32> class directly. Does this introduce boxing conversions, more type checks, null checks, more levels of indirection, virtual calls, reduced optimizations, prevent method inlining? If so, how can I mitigate some of that?

I am writing a library in which I intend all collection classes to be used through their interfaces. The library is for other developers who might want to use it in a high-performance setting.

Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157
  • 1
    If you are so much worried about performance why not use arrays rather then collection classes – Ankur Feb 15 '13 at 12:00
  • 1
    So you'd rather not know and just blindly use arrays... That's one way. I am not _so much worried_ and just want to know the issues. Only then can one make a good assessment in a particular situation. – Daniel A.A. Pelsmaeker Feb 15 '13 at 12:07
  • 1
    Coz the info is CLR implementation specific and it may change in future versions, that't the whole purpose of VMs - to abstract away details that you should not depend upon – Ankur Feb 15 '13 at 12:14
  • @Ankur: I don't believe this is implementation-specific. The CLI standard (ECMA-335) goes to great lengths specifying virtual dispatch (`virtual`, `newslot`/`reuseslot`, `call`/`callvirt`, etc.). – stakx - no longer contributing Feb 15 '13 at 15:58

1 Answers1

1

Boxing

AFAIK, interfaces do not introduce any additional boxing if the implementing types are reference (i.e. class) types. If the implementing type itself is a value type (i.e. a struct), then that value type will be boxed when assigned to a variable of the interface type:

struct Foo : IFooBar { … }           class Bar : IFooBar { … }
IFooBar foo = new Foo();             IFooBar bar = new Bar();
//          ^                                    ^
//       boxing                              no boxing

This is because interface types are treated like reference types; remember that you could assign null to a IFooBar-typed variable, but not to a Foo-typed variable!

Side note: If the implementing type is a struct, perhaps see this question, too.

Virtual dispatch

However, methods that implement an interface method are internally treated similarly to virtual methods; i.e. they get a slot in a dispatch table like a virtual method would, even if you have not declared the implementing method virtual.

Don't worry too much about this. Virtual method dispatch should not be seen as a problem in an object-oriented language — it's just normal. You're not likely to see any performance issues caused by it.

Community
  • 1
  • 1
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268