Geeks With Blogs
Brian Schroer Don't Call Me Mort!
Technorati Tags:

 

If you use Resharper, you've probably seen it recommend that you make private methods static if they don't use any instance data or methods.

FxCop also has a rule (CA1822) about this:

"Methods which do not access instance data or call instance methods can be marked as static. After doing so, the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that insures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."

The BlackWasp web site (not "Black WASP" - that wouldn't make sense :) did a comprehensive speed test to determine how much of a "measurable performance gain" can really be achieved by making methods static.

Their conclusion? "The results show that calls to static methods are indeed faster than the equivalent calls to instance methods. However, the penalty for using instance methods is minor and should only be noticeable when making many billions or trillions of calls".

As some point out in a Stack Overflow discussion about this question, the recommendation is not entirely about performance. Brian Rassmussen comments "It makes me ask myself if the method in question should actually be part of the type or not. Since it doesn't use any instance data, you should at least consider if it could be moved to its own type. Is it an integral part of the type, or is it really a general purpose utility method?".

And hey, if converting to static is as easy as pressing Alt-Enter with Resharper, why not?

John Saunders mentions on the Stack Overflow page that you can use the Resharper "Make Method Static" refactoring to convert a set of related methods. I did not know that.

BlackWasp has an interesting collection of other Speed Tests, including:

Posted on Saturday, July 3, 2010 5:44 PM .NET | Back to top


Comments on this post: How much faster are static vs. instance methods?

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Brian Schroer | Powered by: GeeksWithBlogs.net