I am using CultureInfo.CurrentCulture
when formating my strings using string.format
To quote this blog
This just has the implication that if you are using CurrentCulture a lot, it might be worth reading it into a private variable rather than making lots of calls to CultureInfo.CurrentCulture, otherwise you're using up clock cycles needlessly.
so as per this author
var culture = CultureInfo.CurrentCulture
string.Format(culture,"{0} some format string","some args");
string.Format(culture,"{0} some format string","some other args");
is better than
string.Format(CultureInfo.CurrentCulture,"{0} some format string","some args");
string.Format(CultureInfo.CurrentCulture,"{0} some format string","some other args");
as per MSDN, CultureInfo.CurrentCulture is a property
Is there a performance penalty associated when accessing a property multiple times ??
Also I did some emperical analysis and my tests show me that using a local variable is more expensive than using the property directly.
Stopwatch watch = new Stopwatch();
int count = 100000000;
watch.Start();
for(int i=0;i<count;i++)
{
string.Format(CultureInfo.CurrentCulture, "{0} is my name", "ram");
}
watch.Stop();
//EDIT:Reset watch
watch.Reset();
Console.WriteLine(watch.Elapsed);
Console.WriteLine(watch.ElapsedMilliseconds);
Console.WriteLine(watch.ElapsedTicks);
Console.WriteLine("--------------------");
var culture = CultureInfo.CurrentCulture;
watch.Start();
for (int i=0; i < count; i++)
{
string.Format(culture, "{0} is my name", "ram");
}
watch.Stop();
Console.WriteLine(watch.Elapsed);
Console.WriteLine(watch.ElapsedMilliseconds);
Console.WriteLine(watch.ElapsedTicks);
Result:
00:00:29.6116306
29611
68922550970
--------------------
00:00:27.3578116
27357
63676674390
My tests show that using CultureInfo.CurrentCulture
property is better than using local variable (which contradicts with the authors view). Or am I missing something here ?
Edit:I was not resetting the stopwatch before teh second iteration. hence the difference. resetting stopwatch, updating iteration count and result in this edit