C#中班级成员的访问时间 [英] Access-time of class members in C#

查看:87
本文介绍了C#中班级成员的访问时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么班级成员的访问时间长?

我创建了一个像这样的简单类:

Why the access time of class members is high?

I created a simple class like this:

class A {
   public SimpleClass()
   {
   }
   public void doSth()
   {
   }
}



通过使用Stopwatch类(在System.Diagnostics中),我测量了
访问doSth()的时间:



And by using Stopwatch class(in System.Diagnostics) I measured the
time of accessing doSth():

myStopwatch.Start();
mySimpleClass.doSth();
myStopwatch.Stop();



结果令我震惊!

尽管该方法不执行任何操作,但访问时间约为:0.04毫秒!
在测量更多计算的时间间隔(数百个浮点数的乘积)时,大约需要0.002毫秒!

1.有什么办法可以减少这段时间吗?
2.我有犯过任何错误吗?
(我很高兴知道有关此主题的更多信息:))



and I was shocked by the result!

although the method does nothing,the Access time was around: 0.04 millisecond(s)!
While measuring the time interval of much more calculations (hundreds of multiplication of float numbers) takes about 0.002 ms!

1.Is there any way to reduce this time?
2.Have I made any mistakes?
(I would be happy to know further info. on this topic :) )

推荐答案

进行1000次测试并重新检查结果,您会发现有所不同. br/>
单个呼叫延迟可以归因于CLR,JIT编译等的启动时间.
Do your test 1000 times and recheck your results, you should see a difference.

A single call delay can be attributed to startup time of the CLR, JIT compilation etc.


不重置StopWatch并不是唯一的错误.

更为普遍的一件事是:您应该将JIT时间从方程式中移出.我还应注意,您的重复时间非常短,因此该方法的JIT编译将成为一个严重的因素.该方法通常在您首次调用之前是JIT编译的.而且编译时间比调用本身要长得多.

这是正确的方法:

Not resetting StopWatch is not the only mistake.

One much more general thing is: you should move JIT time out of the equation. I also should note that your repetition time is very low, so the JIT compilation of the method will be a serious factor. The method is usually JIT-compiled before you call it for the first time; and the compilation time is way greater then the call itself.

This is the correct way:

class A {
   // no need in "public SimpleClass() {}"
   internal void doSth() {   } // no need in public: don't provide more access than really required
}

//...

A myInstance = new A();
myInstance.doSth(); // when this has executed, the method is certainly JIT-compiled, but does not have to be compiled sooner

// now, time it!



而已.现在它将正常工作.

—SA



That''s it. Now it will work correctly.

—SA


这篇关于C#中班级成员的访问时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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