Static vs. non-static method

前端 未结 10 1036
执念已碎
执念已碎 2020-11-28 08:30

Suppose you have some method that could be made static, inside a non-static class.
For example:

private double power(double a, double b)
    {
        r         


        
相关标签:
10条回答
  • 2020-11-28 09:07

    Do you see any benefit from changing the method signature into static?

    Three benefits:

    1. Making stateless methods static helps document and clarify their purpose. Otherwise, one is inclined to worry just what mysterious state does the method depend upon?

    2. The static method can be called from other static code, so is potentially more useful.

    3. Static method calls have a smidgin less runtime overhead than instance ones. The compiler can't do that transform automatically -- one reason why is because it would affect use of null. Calling the method on a null reference is required to fail with a NullReferenceException, even if there is no instance state used within the method.

    0 讨论(0)
  • 2020-11-28 09:11

    As defined, power is stateless and has no side effects on any enclosing class so it should be declared static.

    This article from MSDN goes into some of the performance differences of non-static versus static. The call is about four times faster than instantiating and calling, but it really only matters in a tight loop that is a performance bottleneck.

    0 讨论(0)
  • 2020-11-28 09:19

    There should be a slight performance improvement if you declare the method static, because the compiler will emit a call IL instruction instead of callvirt.

    But like the others said, it should be static anyway, since it is not related to a specific instance

    0 讨论(0)
  • 2020-11-28 09:19

    I believe the compiler will not optimise this into a static method. There is a performance gain since the pointer will not have to be checked to see if it is null at runtime. Have a look at the FXCop rule for reference.

    0 讨论(0)
  • 2020-11-28 09:20

    The compiler will likely consider inlining this when it "JITs" the code as it's so short and if it does so then will likely be able to optimise out any reference to the unused this parameter. But you can't rely on any of that.

    You still have to make an object to call it on unless you make it static which has a much bigger overhead anyway if you don't need one for other reasons.

    0 讨论(0)
  • 2020-11-28 09:24

    To me an easy question to decide is "Should I have to instantiate this object just to call this function". In the case of your function, I would say the answer is no, so it should be static. This method does not seem to be related to your object so again, I vote static.

    0 讨论(0)
提交回复
热议问题