Static vs. non-static method

前端 未结 10 1145
执念已碎
执念已碎 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.

提交回复
热议问题