在关注性能时,对DateTime.Today使用变量有多重要? [英] How important is it to use a variable for DateTime.Today when concerned about performance?

查看:101
本文介绍了在关注性能时,对DateTime.Today使用变量有多重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚看到这个被高调的评论


IIRC DateTime.Today 是一个相当昂贵的调用,所以你最好先将值存储在变量中。

IIRC DateTime.Today is a quite expensive call, so you better store the value in a variable first.

这是为了回应一个包含代码的帖子: p>

It was in response to a post that contained the code:

var first = 
    new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-1);
var last = 
    new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddDays(-1);

如果我希望提高性能,请保存 DateTime .Today 在一个变量中,而不是多次调用它?大概有多少使用 DateTime.Today 可以为它创建一个变量?

If I am looking to improve performance, how important is it to store DateTime.Today in a variable instead of calling it multiple times? And roughly how many uses of DateTime.Today would justify creating a variable for it?

编辑: 我意识到我应该测试我的程序,看看是否有性能问题,首先是担心这样的微不足道的事情。为了这个问题,假设我已经做了这个,并且确定需要额外的优化。

I realize I should test my program to see if there are performance problems first before worrying about something as trivial as this. For the sake of this question, assume that I have already done this and determined that additional optimization is needed.

推荐答案

基准我的机器,使用Stopwatch类):

Benchmark (on my machine, using the Stopwatch class):

10,000 DateTime.Today calls and assignment to local variable: 0.0125781 seconds.

10,000 Assignment only operations: 0.0001062 seconds.

代码:

var s = new Stopwatch();
DateTime date = DateTime.Today;
DateTime date2 = DateTime.Today;
s.Start();
for (int i=0; i<10000; i++)
    date = DateTime.Today;
s.Stop();
Debug.Print(s.Elapsed.ToString());

s.Reset();
s.Start();
for (int i=0; i<10000; i++)
    date2 = date;
s.Stop();
Debug.Print(s.Elapsed.ToString());

这篇关于在关注性能时,对DateTime.Today使用变量有多重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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