Difference between CultureInfo.Get and new CultureInfo
When you want to get a CultureInfo
object, you can use the static method CultureInfo.GetCultureInfo
or the constructor of the CultureInfo
class. In this post, I describe the difference between CultureInfo.GetCultureInfo
and the constructor of the CultureInfo
class.
var cultureInfo1 = CultureInfo.GetCultureInfo("en-US");
var cultureInfo2 = new CultureInfo("en-US");
The constructor creates a new instance from the specified culture. You can edit the data from this instance. This means you can change the calendar, the number format, and so on. The following code shows how to change the currency symbol:
var culture = new CultureInfo("en-US");
culture.NumberFormat.CurrencySymbol = "€";
Console.WriteLine(42.ToString("C", culture)); // €42.00
The static method CultureInfo.GetCultureInfo
returns a read-only instance of the specified culture. You can't edit the data from this instance. As you can't edit the culture, the method can cache the instance. So, it can be faster and reduce memory usage.
var culture1 = CultureInfo.GetCultureInfo("en-US");
var culture2 = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine(ReferenceEquals(culture1, culture2)); // True
If you run a simple benchmark, you can see the allocation difference between the 2 methods (see BenchmarkDotNet) and see how the caching can help reduce memory usage.
[MemoryDiagnoser]
public class CultureInfoBenchmark
{
[Benchmark(Baseline = true)]
public void Ctor()
{
_ = new CultureInfo("en-US");
}
[Benchmark]
public void StaticMethod()
{
_ = CultureInfo.GetCultureInfo("en-US");
}
}
Method | Mean | Allocated |
---|---|---|
Ctor | 33.74 ns | 144 B |
StaticMethod | 24.44 ns | 32 B |
In conclusion, you should use CultureInfo.GetCultureInfo
most of the time as it's very uncommon to edit a CultureInfo
object.
#Additional resources
- Pull request that inspired this post: meziantou/Meziantou.Framework#567
Do you have a question or a suggestion about this post? Contact me!