Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable inside or outside an foreach loop: which is faster/better?

Tags:

c#

foreach

Which one of these is the faster/better one?

This one:

List<User> list = new List<User>();
User u;

foreach (string s in l)
{
    u = new User();
    u.Name = s;
    list.Add(u);
}

Or this one:

List<User> list = new List<User>();

foreach (string s in l)
{
    User u = new User();
    u.Name = s;
    list.Add(u);
}

My newbie-developing skills tells me the first one is better, but a friend of mine tells me im wrong, but could not give me a good reason why the second one is better.

Is there any difference in performance at all?

like image 597
Marcus Avatar asked Dec 10 '09 23:12

Marcus


People also ask

Is it bad to declare variables in a loop Java?

All the variables which are used in the program are declared in the beginning. It is better to declare the variable in the loop as its validity will be only up to that block and the code can stand alone for that section. So, to tell there is no difference in anything if either of the approaches are used.

Is it good to declare variable inside for loop in Java?

It's the result of JVM specifications... But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used). It is the result of the JVM Soecification, not 'compiler optimization'.

How do you declare a variable in foreach?

It is necessary to enclose the statements of foreach loop in curly braces {}. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.


2 Answers

Performance-wise both examples are compiled to the same IL, so there's no difference.

The second is better, because it more clearly expresses your intent if u is only used inside the loop.

like image 195
dtb Avatar answered Oct 18 '22 09:10

dtb


In any case, the best way would be to use a constructor that takes a Name... or, otherwise, exploit curly-brace notation:

foreach (string s in l)
{
    list.Add(new User(s));
}

or

foreach (string s in l)
{
    list.Add(new User() { Name = s });
}

or even better, LINQ:

var list = l.Select( s => new User { Name = s});

Now, while your first example could, in some cases, be unperceptibly faster, the second one is better because it's more readable, and the compiler may discard the variable (and omit it altogether) since it's not used outsid the foreach's scope.

like image 33
Tordek Avatar answered Oct 18 '22 09:10

Tordek