HOW IMPORTANT IS IT TO USE A VARIABLE FOR DATETIME.TODAY WHEN CONCERNED ABOUT PERFORMANCE?

Tanuj Kumar

Total Post:134

Points:940
Posted by  Tanuj Kumar
C# 
C#
 1365  View(s)
Ratings:
Rate this:
Hi All!

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.

Thanks in advance!

  1. AVADHESH PATEL

    Post:604

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

    Hi Tanhuj!

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

    10,000 Assignment only operations: 0.0001062 seconds.

    code as given below

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

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

    I hope it resolve your problem

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!