C#:使用静态方法的性能公共类, [英] C#: performance public class with static method,

查看:179
本文介绍了C#:使用静态方法的性能公共类,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将方法声明为静态会影响C#中的性能或ram使用吗?



假设我有50个网页用户同时创建50个单独的网页下面的示例类的实例。



我希望WorkerStatic比Worker更有效 - 至少对于Independent()方法。



引用公共变量(workerCount)的方法应该没有区别,因为它们总是必须在实例中创建。



我尝试过:



Test.aspx

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



TestStatic.aspx

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





Worker.cs



Worker.cs

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(); }
}

推荐答案

否。

对于某种方法,没有显着的性能差异 - 代码仅为所有实例加载一次,无论它是静态的还是与实例相关的。单个实例没有获得该方法的单独副本,因为它的代码是无论如何都是只读的!
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!


静态和非静态方法之间的内存使用和性能没有显着差异。唯一的区别是非静态方法对类实例有一个隐藏参数。这会导致执行一段时间的代码更多的字节。但它可以忽略不计。



但静态方法无法访问其他非静态类成员。因此,示例中的函数 GetWorkerStatic()仅在 workerCount 也是静态时才起作用。然后所有实例将分享可能不是你想要的那些。
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.


这篇关于C#:使用静态方法的性能公共类,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆