Suppose you have some method that could be made static, inside a non-static class.
For example:
private double power(double a, double b) { return (Math.Pow(a, b)); }
Do you see any benefit from changing the method signature into static? In the example above:
private static double power(double a, double b) { return (Math.Pow(a, b)); }
Even if there is some performance or memory gain, wouldn't the compiler do it as a simple optimization in compile time?
As static methods don't operate on instance members, there are a few limitations we should be aware of: A static method cannot reference instance member variables directly. A static method cannot call an instance method directly. Subclasses cannot override static methods.
Java has both static and non-static methods. Static methods are class methods, and non-static methods are methods that belong to an instance of the class. Static methods can access other static methods and variables without having to create an instance of the class.
Method declaration as static or non static is nothing to do with Apex Trigger Best Practice. Difference is that Static method can acces static variable and belongs to the class whereas Non Static method and variables can be accesed only the object of the class.
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class. Static method is declared with static keyword.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With