The for loop using an indexer can introduce some serious performance
problems, but only in some situations. Take for example iterating over
an array returned by a property:
int numItems = myClass.Property.Length;
for (int i = 0; i < numItems; i++)
{
... do something with myClass.Property[i] ...
}
This can incur a serious performance penalty if myClass builds a return
array for every reference to myClass.Property. However,
foreach (Item t in myClass.Property)
{
... do something with t...
}
incurs no such penalty, because the array is fetched from
myClass.Property once and then the enumerator ranges over the one
array.
(To wit, I'm talking about a property that may look like this:
public class TheClass
{
public Item[] Property
{
get
{
Item[] result = new Item[this._internalArray.Length];
for (int i = 0; i < this._internalArray.Length; i++)
{
result[i] = this._internalArray[i].Clone();
}
return result;
}
}
}
As you can see the array gets copied every time, which makes the for
loop with indexer in the code using this property a real performance
hog!)