-2

I have noted in c# that using var improves your performance, especially when declaring variables of a specific class. I have done multiple bench marks and have got the same result every time. I have also read similar questions on this site and others. but no one has actually commented on this. Can anyone please confirm or refute this. I have a class for image data, clsImageData and collection clsImageDataCollection. a function in collection class is SetCaseLowerCase(). Code is

private void SetCaseLowerCase()
{ 
   foreach (var item in this) 
   { 
      item.DestinationImageName = item.DestinationImageName.ToLower(); 
   } 
} 

Now if I use clsImageData instead of var, it performs slower, I have checked it with 100000 iterations. but results is always the same. also with other examples too. Thanks

Edited I have tested this simple code and got 7/10 times better performance using var. Please tell me what am I doing wrong, I am using VS 2017, debug mode for any CPU, my processor is quad core. Thanks

            sw.Start();
            for (int i = 0; i < 10000000; i++)
            {
                var xyz = "test";
            }
            StopClock(sw, "Example var - ");
            sw.Start();
            for(int i = 0; i<10000000; i++)
            {
                string xyx2 = "test";
            }
            StopClock(sw, "Example type - ");
Suhaib
  • 1
  • 1

1 Answers1

1

var is compiled in a way, that makes the use of it equals to just declaring the variable/ type (except in cases it cant be done somehow else but using var ex: anonymous types). that means there are no performance changes at all. read more about var at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var

here is a demonstration, type the following code:

var list = new List<int>();

note that when you hover above list your IDE says:

(local variable) List<int> list

the reason for that is that var is converted to the declared type, meaning that var is actually cosmetic and its use can not impact any performance.