Is it worth to create new variable to use array instead of list?

I want to have the best performance and I know that array its faster than list but with array I need to create a variable for counter and even may need to use .Count or .Length to find the size so I though maybe better just use list? Below are the examples.

Example 1:

foreach (var item in items)
    ItemCollection.Add(item);

Example 2:

int i = 0;

foreach (var item in items)
{
    ItemCollection[i] = item;
    i++;
}

Example 3:

for (int i = 0; i < items.Count; i++)
    ItemCollection[i] = item;

Answers


Performance of a list is nearly identical to that of an array. If you know the exact number of items that you are planning to add, you can eliminate the potential memory overhead as well by creating a list with the exact number of elements to avoid re-allocations on Add:

// Reserve the required number of spots in the list
var ItemCollection = new List<ItemType>(items.Count);
foreach (var item in items)
    // Add is not going to cause reallocation,
    // because we reserved enough space ahead of time
    ItemCollection.Add(item);

In most instances, this turns out to be a premature micro-optimization.


Example one is your best option as it appears you are trying to dynamically change the size of your array/list,

Example two is just silly.

And example 3 would become tricky when you wish to extend the array. See my first point

A point to note in your third example is in your for loop you have

 for (int i = 0; i < items.Count; i++)

This will revaluate items.Count every iteration so you could micro-optimize by moving this out of the for loop

var length = items.Count
for (int i = 0; i < length; i++)

Need Your Help

Retina issue (OS X)

osx cocoa retina-display

I am creating a Cocoa app, and when I import @2x images into my project, no image shows up in the app at all. I am using a non-Retina MacBook Pro.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.