开发者

Are Extension methods too expensive?

How much will it cost for my programs performance if i add Extension methods to it?

Will it work slower or may be will load slo开发者_Python百科wer?

Thanks.


How much will it cost for my programs performance if i add Extension methods to it? Will it work slower or may be will load slower?

There will be no performance hit. Extension methods are really static methods.


An extension method is just syntactic sugar applied to a static method.

In theory, a static method is faster than a non-virtual instance method (no need to check for null this) which in turn is faster than a virtual instance method (no need for looking up the implementation to call).

In theory also, optimisations could get rid of these differences. It's also overstated in terms of static when it comes to extension methods, since the object is probably going to be dealt with in such a way as requires a null-check (whether explicit or implicit to the ways it is use) anyway.

In practice, the chances are that whatever the extension method does will have much, much more of an impact that whether it's extension or instance.


I quickly performance tested this using some integer extension methods in a REALLY long running loop and found that in the cases I tested, the performance was generally identical. When debugging or running unoptimized assemblies, extension methods ran about twice as slowly as my control cases, this makes sense because the debugger can't inline these methods and has to keep track of the callstack, etc.

So, in an assembly ready for release, no performance penalty.


It certainly won't load slower, as loading a program is not dependent on the execution paths in the program.

As for running more slowly? Only measuring the time taken for the extension method and the non-extension method will show for certain. I suspect the difference won't be significant even if it's actually measurable.

The important consideration should always be "does the extension method make my code clearer and easier to understand and maintain".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜