This is a mirror of official site: http://jasper-net.blogspot.com/

The Darkness Behind DateTime.Now

| Thursday, May 26, 2011
A short while ago David Penton and Peter Bromberg had a conversation on Twitter about performance differences between using DateTime.Now and DateTime.UtcNow properties and the best practices related to them. I jumped in their discussion with my thoughts and Peter did a nice job by putting a summary on EggHeadCafe. While that summary suffices for many developers to understand the problems associated with wrong usage of DateTime.Now (which is very commonplace), I thought that it may be a good idea to dedicate a blog post to this topic with more details for two reasons: first, we need to repeat certain stuff to spread the word about a good or bad practice and inform developers about it, and second, it may be worth seeing the reasons, numbers, and performance measurements for everyone to understand the points.

In this post I’m going to discuss the applications of two properties of DateTime structure, Now and UtcNow, as well as Stopwatch class, and provide a set of measurements of performance impacts associated with each one.

DateTime.Now
A very commonly-used and well-known property of the DateTime structure in .NET is Now which simply returns the current date and time on the machine executing the code. Such a property is provided in almost all programming languages as a built-in feature and has many applications. Unfortunately, most of the .NET developers have been misusing this property for years for purposes other than what it’s supposed to serve for. I can outline two possible reasons for this problem:

Most of the developers are careless about all the properties and methods provided by built-in types in a language, so they don’t discover all the details about them. In fact, they use something that just solves their problem regardless of the side-effects.
The traditional use of similar methods in languages used by .NET developers in the past has left some bad habits for them while the internal working of this property is slightly different from what is available in some other languages.
I have to admit that I was a developer who used to apply this property for wrong purposes in the early years of my .NET development, and may still misuse that for simple codes where I don’t care much about performance, but it’s not something to use in each and every situation.

Read more: .NET Zone

Posted via email from Jasper-net

0 comments: