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.
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
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.
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.
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.
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.
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.
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)
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.
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]
Related
Straight up question: If I run code analysis, it tells me to make methods static even in nonstatic classes.
As far as I know, static methods are JITed and run on the Type-Object in the Heap. So wouldn't make a method static in a non static class mean, that the instance has to search the type object in the Heap and run the method there?
Wouldn't that mean a performance issue? Sure it would not be that big of a deal, but I'd still be interested on this.
No, it doesn't work like that.
A static method is actually (imperceptibly) more efficient than a non-static one because (a) it does not have a hidden "this" pointer passed to it and (b) because it's static, the framework doesn't have to do anything about it being virtual (although that last point also applies to non-virtual member methods too, of course).
Here is an in-depth article about CLR runtime type handling. In particular, look at the information there about the MethodTable and the Method Slot Table.
Here's another good article from Joe Duffy. It doesn't explicitly talk about static methods, but it does explain how method calls are made at the lowest (assembler) level, so you would be able to see why a static method call is efficient.
Good post about performance comparsion of static methods vs instance methods: Performance of static methods vs instance methods
TLDR:
Mostly the performance costs of instance vs static are below
negligible.
What costs there are will generally come where you abuse
static for instance or vice-versa. If you don't make it part of your
decision between static and instance, you are more likely to get the
correct result.
There are rare cases where static generic methods in another type
result in fewer types being created, than instance generic methods,
that can make it sometimes have a small benefit to turn rarely used
(and "rarely" refers to which types it's used with in the lifetime of
the application, not how often it's called). Once you get what he's
talking about in that article you'll see that it's 100% irrelevant to
most static-vs-instance decisions anyway.
I think the point is that you're not calling a static method upon an instance, but on the class itself. Any method that does not directly rely on instance information could (and based upon code analysis also should) be marked static and then be called like this:
NonstaticClass.TheStaticMethod();
instead if this
NonstaticClass inst = new NonstaticClass();
inst.TheStaticMethod();
This is because less overhead is required to look up and run a static method than a non-static method on a class instance.
I use static methods for things I really MEANT to be static. I use ReSharper for better code quality. Sometimes ReSharper suggests that a method can be made static.
When I got the following class:
public class WhatEverClass {
private string DoSomethingFancy(string input)
{
string fancyStuff;
// Fancy Stuff here
return fancyStuff;
}
public WhatEverClass() {
string awesome=DoSomethingFancy("some fancy string");
}
}
ReSharper might say "DoSomethingFancy can be made static".
I know it could be made static, but is there a good reason to really do this? Or should I just ignore these suggestions?
By defining a method static, so a procedure that computes something, you manifest an intent to a consumer of your API about statelessness of your function.
When we use static function, we do not expect it saves a state of computation or some computed internal value somewhere in it's internal static private variables, so the next call to that function may have different result even with the same parameters passed during the first call.
In short: whenever you see a function that just executes an action over parameter and not preserve some state, it is a good candidate for making it static.
If your method doesn't need to say or change the state of an instanciated object, then it should be static.
The usual notion is , if you are not creating an instance of anything, you could declare it static. As to where it should be used, ReSharper gives you suggestions based on standard programming practices. However, i take 'standard programming practices' with a grain of salt. Its a matter of personal programming preference for some. Here is a detailed reference on the topic :
http://msdn.microsoft.com/en-us/library/79b3xss3.aspx
Because you will invoke the WhatEverClass() method from outside the class by creating WhatEverClass instance. So the value for every instance will be different, because the variable is local, and will be created every time you create an instance of the class.
But if you want to keep the same value for all instances, then you can make it static so it will be created once in a memory and all instances will use it.
Beware the consequences of making a method static!
By making your method static, you make it that much harder for consumers to stub out your implementation of the algorithm and replace it with one of their own (obviously if the method is private you have no such worries).
Consumers of your static method have your implementation baked in to their code - they cannot use dependency injection to resolve a specific instance of your algorithm (without a bit of work). This makes their system that much harder to test, and in general lends itself to a less extensible code base.
If the method DoSomethingFancy does not use anything in the object WhatEverClass then it should, in my book, be made static since it does not in fact have anything to do with the object in which it is used.
I run Code Analysis and got this message:
CA1822 : Microsoft.Performance : The 'this' parameter (or 'Me' in
Visual Basic) of 'CreateIntervalString(TimeSpan)' is never used. Mark
the member as static (or Shared in Visual Basic) or use 'this'/'Me' in
the method body or at least one property accessor, if appropriate.
My code is:
private string CreateIntervalString(TimeSpan timeSpan)
{
return timeSpan.ToString();
}
as I understood, because CreateIntervalString function does not use any the members of the class, and only uses on the timeSpan input, VisualStudio recommends me to mark it as static.
My Questions:
Why when I mark it as static, the performance is improved?
My function is part of library that should be thread-safe, does marking method as static prevent this?
I have additional private functions that use only its inputs, and does not use at any other members of the class, yet I don't get the same error for them.
Thanks a lot!
Examples:
the following method provides an error:
private string CreateIntervalString(TimeSpan timeSpan)
{
return timeSpan.ToString();
}
and the following does not:
private DateTime ParseDateString(string dateTimeString)
{
// the years,monthe,days,hours,minutes and secondes found by the dateTimeString input
return new DateTime(years, months, days, hours, minutes, secondes);
}
The MSDN site http://msdn.microsoft.com/en-us/library/ms245046.aspx gives the answer to the performance aspect
If the method is not marked as static then the current object (this) will be checked against null by the runtime. In most cases there will be little observable difference, it's true, but if a method which is called millions of times per second can get that gain by being made static then it could be worthwhile.
The performance is not improved (in any way that matters), but the code gets clearer. The method doesn't make the impression that it uses the instance, and you can use the method without creating an instance of the class.
As you are not using the instance from the method, it doesn't affect the status of thread safety. As the method only uses the data that is sent to it, it is thread safe.
Either you actually use some instance member in the methods, there is something in the code that could potentially use some instance member, or there is something in the code that makes the tool think that it does.
Static functions have one less argument (the hidden this argument), so theoretically they are somewhat more efficient.
Thread safety has nothing to do with whether your method is static or not. You can make an instance method thread-unsafe just as easily as a static method.
Could you post some of those functions for us to see?
In most situations, you won't notice a performance difference between static and non-static functions. Theoretically, the fact that they cannot be virtual (and don't push the "this" pointer as an argument) make then slightly faster. But again, not something you would usually notice.
Static and thread-safety are not related. If the method was thread-safe before "static", it will be thread-safe after "static".
I have seen this before with some tools. If the additional private methods are used by non-static methods, the code analysis will assume they cannot be made static (even if they do not reference members). If you change the other non-static methods to static (if you can) then it will probably give you the same warning.
Hope that helps,
John
Is there a best practice for making private methods in classes static? I have a class with a few methods. Some of these can easily be made static, since they simply process data.
Should I make them static or just leave them as is? Is this more of a style issue? Are there performance considerations?
Edit:
Method can be made static, but should it?
If the methods don't access any of the type's state then they should be static.
Static method calls provide a performance gain over instance methods and the presence of a static method tells future readers of your code that calling this method will create no side effects in the the state of the current instance of the type.
The performance gain of a static method comes from the fact that the compiler does not have to emit callvirt instructions to call a static method. The callvirt instruction is handy for instance calls in that it does a null check prior to calling the method. However, when you call a static methods there is no need to check for null so the compiler is free to emit the faster call instruction which doesn't check for null.
As Dan Diplo says, if they can be made static, they should be made static. This is only true for private static methods (which is what you asked about). For public methods, however, they will just confuse users of your class. Public methods should be made static only if they will be used without an instance of the class by callers, the performance loss of not making them static be damned.
I always think if they can be made static (and the compiler will soon let you know if they can't) then they should be made so. See this duplicate question on SO for further discussion.
I only make methods static when i am sure that they don't have any side effects.
If a method doesn't use any instance data in the class, it should be static. That way it's clear that it's independent of the instances, and that you don't have to create an instance to call it.
Any performance differences should not be a concern. There is of course a difference in how a static method and an instance method are called, but you will most likely not be able to measure any consistent performance difference. The difference is so small that sometimes calling an instance method might actually be faster just because the instructions happens to line up better in the execution.
I agree that all private methods that can be static should be static. Just remember the performance variation between the 2 are insignificant so don't do this in an attempt to increase performance since early optimization is likely to cause more failures than successes until you know for sure you have a performance issue and profile your application.
Think about the static methods and multi-threading. You must be very careful.
This discusion is like pattern definition: "a solution for a problem in some context.".
You must not say "This should be done like this." It depends of the context.
If you have a private method that is static, that smells like it could be a method that shouldn't be in the class at all, but should rather be in a library of static methods that can be reused by other classes.
I found that there are two type of methods called static methods and instance methods and their differences.
But still I couldnt understand the advantages of one over another.
Sometimes i feel that static methods are not 100% object oriented.
Are there any performance differences between this two.
Can someone help?
In a perfect OO world there probably wouldn't be any need for static methods (I think Eiffel doesn't have them, either). But at the end of the day what matters is not OO-pureness of your code (C# has enough concepts that aren't strictly pure OO, like extension methods, for example) but rather what you're getting done.
You can use static methods for general helper methods (that don't need a general helper class or state on their own) or things like Color.FromARGB() which behave slightly contructor-like for value types.
In general, any method that doesn't touch an objects state (and therefore is more class-specific than object-specific) can be made static. Performance differences shouldn't really arise. Not very measurable, in any case. Jan Gray's great article Writing faster managed code: Know what things cost has some hard data on this, albeit to be taken with care.
The usefulness of a static method primarily comes when you need to call the method without ever instantiating the object. For example, maybe the static method is there to actually look up an existing instance and return it (an example being a singleton instance).
As others have stated, you can make any method static if it doesn't access state, and you'll get a tiny performance improvement.
If you actually want to be able to call the method on a specific instance though, and get the benefits of polymorphism (i.e. a derived class can override the behaviour of the method), then you should make the it an instance method.
If your classes implement interfaces, then the methods belonging to those interfaces must also be declared as instance methods.
Instance methods are tight to an instance. So you could see one advantage of static methods is not being tight to an instance. Static methods can (if visible) used by other objects to solve their problems. Sometimes this good and needed. Then you have to think about keeping your static methods in the same class or if you start building utility classes for broader use.
I wouldn't see the use of static methods of being "less OO". Static methods is one way to circumvent the shortcomings of OO (especially in single inheritance languages). You can call it a more functional approach (I know it isn't really).
Taking all this is just a bunch of questions that you should ask your code and that should determine if it is better an instance method, a static method of the same class or a static method of another class.
I wouldn't even think about performance issues. It will weaken your design and the difference isn't really that big. Performance is important if you have performance problems.
Instance methods require passing an implicit parameter (the this reference) which make them slightly slower than static methods. But that really should not be the reason to prefer them.
For a related discussion, look at:
Should C# methods that *can* be static be static?
If your method uses non-static data members, don't make it static (you "can't").
If your method does not use any non-static data members, you can make it static, but that mostly depends on your design rather than on whether it uses or not uses non-static members (there's not much difference in performance anyway as Mehrdad said).
If you have NO non-static data members in your class, sometimes it's a best practice to make all the methods static (like in the case of grouping helper functions under one class for the sake of good order).
I'm partially guessing based on the heritage of C# but I suspect it's the same as the other OO languages.
Static methods do not require an object to work on. A good example is something like:
Double pi = Math.PI.
Instance methods do require an object. An example is along the lines of:
Integer x = 9;
Integer y = x.sqrt();
Not all information belonging to a class should need an object instantiated for that class to get access to it. All those constants which can be used for creation of objects (Math.PI, Window.OVERLAPPED, etc) are prime examples of this.
No one is better than the other. It really depends on your requirement. Class methods are called when you want to apply a change to class as a whole. Whereas Instance methods are called when you are not applying change to the class but to a unique instance (object) of that class.
So I dont see a reason why one should be better than the other.