Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static vs. non-static method

Tags:

performance

c#

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?


Edit: What I am looking for are the benefits by declaring the method as static. I know that this is the common practice. I would like to understand the logic behind it.
And of course, this method is just an example to clarify my intention.
like image 450
Elad Avatar asked Jul 26 '09 14:07

Elad


People also ask

When would you not use a static method?

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.

What is static and non static method in Java?

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.

What is difference between static and non static method in Apex?

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.

What is the difference between a method and a static method?

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.


2 Answers

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.

like image 173
jason Avatar answered Sep 29 '22 21:09

jason


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

like image 20
Thomas Levesque Avatar answered Sep 29 '22 19:09

Thomas Levesque