Static vs. non-static method
Asked Answered
D

10

32

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.
Domel answered 26/7, 2009 at 14:21 Comment(2)
@Everyone, I know this is an "ancient" question in development years but it is still relevant today. Many excellent answers below. Need actual performance numbers for your specific scenario? Write a quick program that calls the method enough times (between a var start = DateTime.Now() and var end = DateTime.Now()) to be able to have an elapsed period big enough to compare. Run it a few times with static and a few times without static and compare the difference. Maybe open TaskManager and observe memory usage for each scenario, too.Caravaggio
Just for completeness, instead of comparing the difference between the two DateTime.Now(), use the StopWatch class. EDIT - Why? It's more accurate and easier to use than the DateTime.Now() way.Pressor
C
9

Note that it is highly unlikely the compiler is even allowed to make that change on your behalf since it changes the signature of the method. As a result, some carefully crafted reflection (if you were using any) could stop working, and the compiler really cannot tell if this is the case.

Craniometry answered 26/7, 2009 at 15:57 Comment(0)
A
36

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.

Artifice answered 26/7, 2009 at 14:27 Comment(1)
Good link, but take it with a grain of salt as it's from 2003. For example, invoking a delegate is not 8x slower than invoking an instance method, but today it's closer to 2x slower.Touchline
C
9

Note that it is highly unlikely the compiler is even allowed to make that change on your behalf since it changes the signature of the method. As a result, some carefully crafted reflection (if you were using any) could stop working, and the compiler really cannot tell if this is the case.

Craniometry answered 26/7, 2009 at 15:57 Comment(0)
R
8

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

Radio answered 26/7, 2009 at 14:27 Comment(0)
D
3

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.

Dealings answered 3/11, 2014 at 0:42 Comment(0)
O
2

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.

Oculo answered 26/7, 2009 at 14:27 Comment(3)
@Cody C: But how does one go about answering the question "Should I have to instantiate this object just to call this function?"?Artifice
IMO its just a matter of "Do I need an object with state if I want to use this functionality?" If I'm just instantiating an object to do a simple function, then that answer is typically no.Oculo
The example in question is private, so this would not be a consideration in this case (it would only be if it was public). The only consideration in this case is the matters that relates to performance.Borborygmus
N
2

Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.

Navy answered 22/5, 2012 at 10:51 Comment(0)
T
1

this method should be static because it is not related to your class or member of classes. it just works with the inputs to this function.

maybe you may need to call it without creating that class. so if it is static it is ok but if it is not, you cant call it without any instance of that class.


Advantages of a static method:

There's no need to create an object first. The method is available immediately.

It's a good when you have generic functionality that does not depend on the state of a particular object. For example, look at the Arrays class or the Collections class from java.util.

Static methods can be good for factories. Pass your requirements as parameters, get a brand new object back. Not a constructor in sight.

Disadvantages of a static method:

You don't have an object instance, so you only have access to static members and your own local variables. If you want an instance, you probably have to create it yourself.

You can create subclasses, but a static method can't be abstract, so it's harder to decouple your implementation from a caller.


(ps: i dont think compiler will optimize if it is going to be static or not.. but not sure)

Teyde answered 26/7, 2009 at 14:24 Comment(0)
M
1

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.

Maneating answered 26/7, 2009 at 14:30 Comment(1)
You already have the object (this) as the example is for a private method.Borborygmus
W
0

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.

Winsor answered 26/7, 2009 at 14:28 Comment(0)
T
-4

i hope we need to define the difference between static and non-static method. Here i am posting few easy lines of code to visualize the conceptual difference.

public class StaticVsNonStatic
{
     public string NonStaticMethod() //non-static
     {

         return "I am the Non-Static Method"; 

     }

     static public string StaticMethod() //static
     {

         return "I am Static Method";
     }

 }

Now lets create an aspx page try to access these 2 methods defined in the class.

 public partial class StaticVsNonStatic_StaticVsNonWorkplace : System.Web.UI.Page
 {
     protected void Page_Load(object sender, EventArgs e)
     {

        StaticVsNonStatic objStaticVsNonStatic = new StaticVsNonStatic();
        lblDisplayNS.Text = objStaticVsNonStatic.NonStaticMethod(); //Non Static 
        lblDisplayS.Text =  StaticVsNonStatic.StaticMethod();  //Static and called without object
     }
 }

Thanks and please post you comments.

Best Regards, Pritom Nandy [Bangladesh]

Trompe answered 26/12, 2010 at 4:20 Comment(1)
Elad clearly already knows how to call a static method. As you're just getting started answering questions on this site, I would suggest looking for questions that don't have an accepted answer yet. You can tell because when searching for questions, the number of answers is yellow if there's an accepted answer and white if not. There's a red background if no-one has tried to answer the question yet, which are the best ones to look at. Welcome to stackoverflow :)Eatmon

© 2022 - 2024 — McMap. All rights reserved.