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
Do you see any benefit from changing the method signature into static?
Three benefits:
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?
The static method can be called from other static code, so is potentially more useful.
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.
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.
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
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.
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.
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.