开发者

.NET getting the Now property cost

Useless question I guess, but accessing the property DateAndTime.Now computes each time the current system date and time, I suppose, is that right?

Thus it would be just a liiiiiittle better to favor:

Dim rightNow As Date = Now
For i 开发者_StackOverflowAs Integer = 0 To 1000
    If expiration < rightNow Then
        '   ...
    End If
Next

Over

For i As Integer = 0 To 1000
    If expiration < Now() Then
        '   ...
    End If
Next

Am I right?


You would be correct, you'd only want to make the Now() call as often as needed.


That depends on what you want to achieve.

If you require all iterations to use the most accurate time, then Option 1 is the way to go.

If you require all iterations to use the same time, then Option 2 is the way to go.

I wouldn't worry too much about the performance of calling DateTime.Now, unless you have already confirmed that it makes a difference for your application. Making sure your program behaves correctly is more important.


DateTime.Now does a lot of processing:

public static DateTime Now
{
  get
  {
        DateTime utcNow = DateTime.UtcNow;
        bool isAmbiguousDst = false;
        long ticks = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utcNow, 
              out isAmbiguousDst).Ticks;
        long num = utcNow.Ticks + ticks;
        if (num > 3155378975999999999L)
        {
              return new DateTime(3155378975999999999L, DateTimeKind.Local);
        }
        if (num < 0L)
        {
              return new DateTime(0L, DateTimeKind.Local);
        }
        return new DateTime(num, DateTimeKind.Local, isAmbiguousDst);
  }
}

It converts the utcNow to your local time. Because of the this calling is expensive. Depending on your requirements, the first sample will give you better performance.


This is easy to test. Here are the average timings on my computer:

00:00:00.0000260

00:00:00.0015428

Is that a meaningful difference? Only you know if it is for your application. And as others have pointed out, how accurate do you need Now() to be?


You're right, however rightnow won't be rightnow as soon as you've done the assignment...if you get my drift.

I'd be interested in seeing some timings to see how much of a difference there is between the two methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜