Thursday, July 8, 2010

Culture Performace .NET 3.5 vs .Net 4.0

Submit this story to DotNetKicks

After converting an application from .net 3.5 to .net 4, I noticed the performance was really reduced at the application startup, where it loads and processes lots of Quote data.

The Performance Wizard clearly showed that the function doing the most work was System.DateTime.Parse(string). If I changed the Target Framework for the application to 3.5, it was again back to normal behavior.

I then made a test console application with a single loop trying to parse 2000 dates to an array. The elements was processed at the same time in both frameworks, so I was clearly missing something.

Framework Ms
.NET 3.5 4
.NET 4.0 3

I then noticed the only difference, was that I in the initial application changed the current culture in the function that was processing the data, like this: System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("nb-NO"); After adding this culture change to the test app, the .NET 4 framework was using considerable more time than in .net3.5:

Framework Ms
.NET 3.5 398
.NET 4.0 2835

What they changed from .NET 3.5 to .NET 4 did not have time to figure out, but I found an easy solution. Instead of changing the culture of the thread, I set the culture when parsing like this:
.. = DateTime.Parse(feedarr[soucreIndex], CultureInfo.GetCultureInfo("nb-NO"));

It then used 5 ms

Framework Ms
.NET 3.5 6
.NET 4.0 5

I then took it further in using parseexact: DateTime dd = DateTime.ParseExact(feedarr[1], "dd.MM.yyyy HH:mm:ss", CultureInfo.GetCultureInfo("nb-NO"));

It then took 3 ms in .NET 4.0.

Framework Ms
.NET 3.5 6
.NET 4.0 3

In a perfect world we would be no regional settings, but until further we are stuck with parsing the date format. As this post shows it’s important to do it the right way … 3 ms is a lot faster than 2 seconds 2835 milliseconds



Happy programming
Petter Søreide