Question

I was wondering if it was a good practice to instantiate a CultureInfo object repeatdedly in a loop process (few thousand times). This object is required in many Date and String methods to force a specific culture when CurrentCulture may not be the right one.

var c = new CultureInfo("en-US", false);

What is the performance of a repeated instantiation?

Était-ce utile?

La solution

One would think that the optimizer in the C# and/or the JIT compilers would have the smarts to recognize a loop-invariant expression and refactor outside of the loop. My inclination is to do such refactorings myself as is makes the code clearer.

Even better, use this method:

CultureInfo ci = CultureInfo.GetCultureInfo("en-US") ;

It gives you a cached, read-only instance, the instance will only be constructed once and thence retrieve from cache.

Better yet, for your stated purposes:

This [CultureInfo] object is required in many Date and String methods to force a specific culture when CurrentCulture may not be the right one.

use CultureInfo.InvariantCulture. That is what it exists for.

A third option, would be to create a static CultureInfo property holding a singleton reference to your fallback culture. Depending on your purposed, you might want to mark it as thread-local (static methods of CultureInfo are thread-safe; instance methods are not). Such a propery might look something like this:

public static string FallbackCultureId { get { return Configuration.AppSettings["FallbackConfigurationId"] ; } }

public static CultureInfo FallbackCultureInfo
{
  get { return fallBackCultureInfo ?? (fallBackCultureInfo=new CultureInfo(FallbackCultureId)) ; }            
}
[ThreadStatic] private static CultureInfo fallBackCultureInfo ;

Autres conseils

Why not just declare the culture outside of the loop and use the instance reference inside of the loop?

The more you put in there the longer it will take

In case it is for winforms/wpf app: How to: Set the Culture and UI Culture for Windows Forms Globalization

// C#
// Put the using statements at the beginning of the code module
using System.Threading;
using System.Globalization;
// Put the following code before InitializeComponent()
// Sets the culture to French (France)
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
// Sets the UI culture to French (France)
Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top