9

The language I use is C#.

Let we have a List of objects of type T,

List<T> collection = new List<T>{.....};

Say that we want to go over each item of collection. That can be done in many ways. Among of them, are the following two:

foreach(var item in collection)
{
   // code goes here
}

and

foreach(T item in collection)
{
    // code goes here
}

Does the second way be better than the first or not and why?

Thanks in advance for your answers.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • 14
    `exactly the same` – L.B Dec 09 '13 at 14:19
  • 7
    There is no such thing as `var` at runtime. The two will emit identical compiled code. – David Dec 09 '13 at 14:21
  • `var` is just a nice way to not have to write out types. The compiler will replace var with the actual type, so it makes zero difference to the end result. – Tobberoth Dec 09 '13 at 14:21
  • 1
    The only thing to be aware of is if you do something that causes the compiler to emit a cast action for the type when you are creating the `foreach`. For example, `List o;` `foreach (string i in o)` will add IL calls to attempt to cast the iterator's current item to a string. This is a throwback to supporting the old .NET collections. – Adam Houldsworth Dec 09 '13 at 14:26
  • 1
    A faster way *may* be to use a `for` over the `foreach`, I have read that it does perform better under certain conditions. – James Dec 09 '13 at 14:31
  • 2
    **Measure it and find out.** You've written the code both ways; now run it and see which is faster. – Eric Lippert Dec 09 '13 at 14:52
  • @James you are pretty right. I didn't know it that and I read the article in the following link http://codebetter.com/patricksmacchia/2008/11/19/an-easy-and-efficient-way-to-improve-net-code-performances/, that states that you wrote. – Christos Dec 09 '13 at 14:52

5 Answers5

24

They're both exactly the same. var is syntactic sugar for convenience. It makes no difference to the speed with which a List is traversed.

The rule of thumb I follow with var is to only use it if the type of the object is present on the right-hand side of an assignment, so in this case I'd prefer to explicitly specify the type in the foreach to make it clearer for other engineers, but it's down to personal choice. If you hover over a var in Visual Studio, it will display the type (assuming it can infer what is should be).

Chris Mantle
  • 6,595
  • 3
  • 34
  • 48
  • 2
    Chris is correct, use of var definitely makes no difference to speed - both loops will be translated into identical bytecode when compiled. – Henry Wilson Dec 09 '13 at 14:22
  • 3
    Sometimes `var` is not just a 'syntactic sugar' but a must. for example when you iterate over a list of anonymous objects. – haim770 Dec 09 '13 at 14:28
  • @haim770 Indeed, it's a must for anonymous types - thanks! – Chris Mantle Dec 09 '13 at 14:31
  • @haim770 Well you don't [*have to*](http://msdn.microsoft.com/en-us/library/System.Reflection.Emit.TypeBuilder%28v=vs.110%29.aspx), but it is a huge PITA if you don't. – Scott Chamberlain Dec 09 '13 at 15:01
  • @ScottChamberlain, 'PITA'? you 'have to' if you want to write a simple `foreach` like you used to write for 'regular' types. – haim770 Dec 09 '13 at 15:06
  • @haim770 Yes, a [PITA](http://en.wiktionary.org/wiki/PITA). It would not be "simple" at all if you did not use `var`, but you could do it. – Scott Chamberlain Dec 09 '13 at 15:10
9

Quoting MSDN:

An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

So

var i = 10; // implicitly typed
int i = 10; //explicitly typed

Are exactly the same.

Now, for 'better' - It'll heavily depend on what's your parameter to judge that. If it's speed, then a for loop may be better than a foreach, and T[] better than List<T>, according to Patrick Smacchia. Main points:

  • for loops on List are a bit more than 2 times cheaper than foreach loops on List.
  • Looping on array is around 2 times cheaper than looping on List.
  • As a consequence, looping on array using for is 5 times cheaper than looping on List using foreach (which I believe, is what we all do).

Quote source: In .NET, which loop runs faster, 'for' or 'foreach'?

Reference: http://msdn.microsoft.com/en-us/library/bb383973.aspx

Community
  • 1
  • 1
OnoSendai
  • 3,960
  • 2
  • 22
  • 46
3

If you compare the IL code then you will see that the are really 100% the same. var is only syntactic sugar:

C# Code:

  List<int> collection = new List<int>();
  collection.Add(1);
  collection.Add(2);
  collection.Add(3);

  foreach (var myInt in collection)
  {
    Console.WriteLine(myInt);
  }

  foreach (var T in collection)
  {
    Console.WriteLine(T);
  }

 bool flag;

            System.Collections.Generic.List<int> list = new System.Collections.Generic.List<int>();
            list.Add(1);
            list.Add(2);
            list.Add(3);
            System.Collections.Generic.List<int>.Enumerator enumerator = list.GetEnumerator();
            try
            {
                while (flag)
                {
                    int i1 = enumerator.get_Current();
                    System.Console.WriteLine(i1);
                    flag = enumerator.MoveNext();
                }
            }
            finally
            {
                enumerator.Dispose();
            }
            enumerator = list.GetEnumerator();
            try
            {
                while (flag)
                {
                    int i2 = enumerator.get_Current();
                    System.Console.WriteLine(i2);
                    flag = enumerator.MoveNext();
                }
            }
            finally
            {
                enumerator.Dispose();
            }
Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70
1

There is no faster way to iterate through same collection.

No matter what you use, your own loop or extension methods - this is all the same. When you use var - it still compiles to the same thing.

The only difference might be that if you use Dictionary, it will be faster than the List<T> or Collection in terms of searching for values. Dictionary was designed with optimization for search

T.S.
  • 18,195
  • 11
  • 58
  • 78
0

1st way (with var) might be better for readability. Consider this:

List<User> list = new List<User>();
var users = list.GroupBy(x => x.Name).OrderBy(x => x.Key);
foreach (var user in users)
{
 //blah
}

vs

foreach (System.Linq.IGrouping<string, User> user in users)
{
}

I believe that was the main reason for having var in the first place.

Evgeni
  • 3,341
  • 7
  • 37
  • 64
  • 1
    That's a pretty bad example of *"better readability"*. Considering it's using a fully namespaced type + it's a group and the username is `user`. I'd argue this is an *ideal* candidate to use the `var` keyword. – James Dec 09 '13 at 14:42
  • @James Ups.. I meant the 1st way. – Evgeni Dec 09 '13 at 14:48
  • I must agree with @James on this. The two blocks aren't equal. And readability, like beauty, is also on the eye of the beholder; The first three lines of the first block helps understanding much more than the second block. – OnoSendai Dec 09 '13 at 14:49
  • @OnoSendai foreach (var user in users)... and foreach (System.Linq.IGrouping user in users) do same thing, you agree ? With linq results I often don't care to know the exact type, so I much rather prefer to use var vs typing out 30-char long type - and I strongly believe that 99% od devs would feel the same, no ? – Evgeni Dec 09 '13 at 14:54
  • @Eugene What I meant is that the two blocks aren't equivalent; Which part of the 2nd implies ordering? And something I learned very early as a coder was 'never assume anything'; personal preferences have nothing to do with, say, code maintainability, and with heavy usage of anonymous typing you may be making the life of the junior programmer that'll come after you VERY hard. – OnoSendai Dec 09 '13 at 15:06
  • @OnoSendai Care to explain how are they not equivalent? How do you code without making assumptions (e.g. you do assume that .NET code was tested and works as it should, no?)? What makes you think I'm making heavy use of vars (no assumptions, eh?) ? And what do you mean by "Which part of the 2nd implies ordering?" ? That was just an example, if anything. – Evgeni Dec 09 '13 at 15:15
  • @Eugene comments are hardly the best place to go on with this. Feel free to ask this as a new question, and let others discuss similarities (or lack thereof) as well. – OnoSendai Dec 09 '13 at 15:25
  • Agreed, not a best place. However, I don't feel that its me who needs to be educated on this matter. But lets end this. – Evgeni Dec 09 '13 at 15:28