开发者

Performance gain of marking class methods as static

I am using FxCop to look for improvements on our application. One of the rules we are often breaking is "Mark members as static" which is marked as a performance rule.

Certainly we have a lot of class methods that do not action on any of the class members, which could be marked as static, but is there really a performance gain to this?

My understanding is that stati开发者_高级运维c will be intantiated once at execution time. If the method is never invoked that it would have been a waste. If the method is invoked multiple times than there might be a small benefit.

With variables there are obvious implications as to whether or not they are marked static, and it is critical to the operation of your application how they are defined. For methods though I don't believe there is any functional affect on whether or not they are marked static if they do not reference any instance variables or methods.

Am I missing the point here? Is the standard to mark all of these methods as static?


Performance becomes better because static method doesn't have hidden "this" pointer.

Every instance (non-static) method has hidden "this" pointer, which is passed to the method to access instance members. If no non-static members are used, "this" pointer remains unused. Passing additional parameter on the stack or in CPU register takes a time which can be saved by declaring such method as static.

"My understanding is that static will be instantiated once at execution time."

Both static and non-static methods exist only once in the program code. Only non-staic data members are duplicated, when there are different class instances. Non-static class method works with specific instance using class reference (hidden parameter). Code itself is never duplicated.


As you said, when a method is marked as static, it is instantiated once, the first time it is used. Whenever subsequent calls are made, the runtime environment doesn't need to validate it, because it is guaranteed to exist. Here is the Microsoft doc for it: http://msdn.microsoft.com/en-us/library/ms245046%28v=vs.80%29.aspx

Here's some more guidance: Method can be made static, but should it?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜