Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach, performance-wise. Should we declare variable once before loop or inside it?

What is better for performance wise declaring the variable outside the foreach statment and the each time reassign it in side it (foreach) or create an new variable inside foreach for example

private List<ListItem> GetItems()
        {
            var items = new List<ListItem>();
            var collection = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            ListItem item;
            foreach (var i in collection)
            {
                item = new ListItem { Text = i.ToString() };
                items.Add(item);
            }

            return items;
        }

or this one?

private List<ListItem> GetItems()
        {
            var items = new List<ListItem>();
            var collection = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            foreach (var i in collection)
            {
                ListItem item = new ListItem { Text = i.ToString() };
                items.Add(item);
            }

            return items;
        }

sure here I'm speak about item object. thank you all.

like image 450
Ahmed Magdy Avatar asked Oct 27 '09 17:10

Ahmed Magdy


3 Answers

This sounds like a premature optimization.

First of all, do you have any reason to believe that there is a performance problem here?

Second, in release builds, the compiler's optimizer will probably produce identical code for both scenarios - so it's likely irrelevant. In debug builds this may not always be true, but there you don't want optimizations since the intent of debug builds is to allow you to accurately step through the code.

like image 64
LBushkin Avatar answered Oct 22 '22 16:10

LBushkin


There is an edge case where this matters; if you "capture" the variable into an anonymous method / lambda. Otherwise it is premature and makes no difference. At all.

An example of when it does matter:

// prints all items in no particular order
foreach (var i in collection)
{
    string s = i.ToString();
    ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(s); });
}

vs

// may print the same item each time, or any combination of items; very bad
string s;
foreach (var i in collection)
{
    s = i.ToString();
    ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(s); });
}
like image 26
Marc Gravell Avatar answered Oct 22 '22 16:10

Marc Gravell


I'm pretty sure the IL generated by your two code blocks is identical. There shouldn't be any change in performance. However the second code block where you declare the type of item right where it is used is slightly more readable and I would use that.

like image 35
Praveen Angyan Avatar answered Oct 22 '22 17:10

Praveen Angyan