开发者

How does indirection introduced by interfaces and factories affect performance?

I would like to improve testability of some legacy code. To achieve this, I am introducing interfaces for existing classes (and have existing classes implement those) and factories that create an instance of a test object or an object of the original class, depending on some configuration setting.

I can foresee some internal feedback along the lines of 'but this will affect performance', but I would like to be able to test some code (for a service layer in this case), without having to deploy all underlying layers and setup a database server.

Do you have any experie开发者_开发问答nce where the indirection introduced did affect performance noticeably? What would be a constructive way to respond to the aforementioned feedback?

Thanks,

Martijn


According to a book from Don Box (Essential .NET volume 1), the effect of calling a function on an interface as compared with calling it on a class is one machine instruction, as there is one more indirection. This would mean that on a 2 GHz processor, it would be 0.0000000005 seconds slower to call an interface method than a class method.

This refers to the .net release 1 implementation (I have an old edition of this book). I am not sure if that changed a lot for newer versions, or how it applies to Mono, but I would definitely not assume dramatic effects.

As you see, on modern computers, the effect should be neglectable except in the rare case that you have to hunt for every nanosecond.


The short answer: It'll make no difference at all.

The longer answer: It'll almost certainly make no difference at all. The only real performance difference should be that method calls through the interface can't be inlined, so any methods which were inlined on the original class will be slower with the interface. However, we're only talking a few extra nanoseconds per call, so if you have inlined methods on the class and if they get called millions of times, then you might see a noticeable difference. However, if you have such a method that's the limiting factor to your application's performance, then the performance junkies will surely have already measured that and be able to tell you. Won't they?


The only difference in a interface method call is that it is guaranteed to be a virtual method call. It would be optional on a direct class instance method call, depending on whether you declared it virtual or not.

In practice it makes no difference, the VB.NET compiler uses the same trick as the C# compiler. It makes an indirect call even if the method isn't virtual, useful for its implicit null reference check. Only a static method call could be cheaper.

There's no point in worrying about this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜