Click here to Skip to main content
15,886,734 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Does declaring a method as static affect performace or ram usage in C#?

Say I have 50 users of a web page at the same time which create 50 separate instances of the example class below.

I would expect that the WorkerStatic is more efficient that Worker - at least for the Independent() method.

And there should be no difference in the methods which refer to the public variable (workerCount), because they always have to be created in the instance.

What I have tried:

Test.aspx
<html><body>
<% var worker = new Worker(); %>
</body></html>


TestStatic.aspx
<html><body>
<% var worker = new WorkerStatic(); %>
</body></html>


Worker.cs
C#
public class Worker
{
   int workerCount = 0;
   public void SetWorkerCount (int count) { workerCount = count; }
   public int GetWorker () { return workerCount; }
   public static string Independent() { return DateTime.Now.ToString(); }
}

public class WorkerStatic
{
   int workerCount = 0;
   public void SetWorkerCount (int count) { workerCount = count; }
   public static int GetWorkerStatic () { return workerCount; }
   public static string IndependentStatic () { return DateTime.Now.ToString(); }
}
Posted
Updated 17-Aug-18 2:55am

No.
For a method there is no significant performance difference - the code is loaded once only for all instances regardless of whether it is static or instance related. The individual instances do not get a separate copy of the method as it's code, which is read only anyway!
 
Share this answer
 
Comments
Sni.DelWoods 20-Aug-18 3:24am    
That's a very good information in general.
So all code of a class exits only one time in the whole project.

I learned that no mather how many code is in the class only variables are instanced - in the example it is only workerCount.

Thank for that.
OriginalGriff 20-Aug-18 3:39am    
You're welcome!
There is no significant difference in memory usage and peformance between static and non static methods. The only difference is that non static methods have a hidden parameter to the class instance. This results in a few more bytes of code which execution took some time. But it is negligible.

But a static method can't access other non static class members. So the function GetWorkerStatic() from your example would only work when workerCount is static too. Then all instances would share that which is probably not what you want.
 
Share this answer
 
Comments
Sni.DelWoods 20-Aug-18 3:12am    
Thanks for your comment.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900