Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How important is it to use a variable for DateTime.Today when concerned about performance?

I just saw this upvoted comment

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

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

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?

Edit: 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.

like image 499
Rachel Avatar asked Apr 03 '13 15:04

Rachel


2 Answers

how important is it to store DateTime.Today in a variable

The best answer to that is to benchmark on the hardware you expect your code to be running on. Unless you are calling it in an extremely tight loop, I doubt it will be a problem.

A better reason to store it in a variable is that you just might roll over from one day to the next between the two calls.

UPDATE

To provide an order of magnitude, @RichardBrown shared in his answer a link indicating that the cost of DateTime.Today is was tested to be on the order of a few hundred nanoseconds (on the particular hardware used for that test).

like image 140
Eric J. Avatar answered Sep 18 '22 05:09

Eric J.


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.

Code:

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());
like image 20
Robert Harvey Avatar answered Sep 20 '22 05:09

Robert Harvey