Game Development Reference
situation is ideal because hardly any marshaling is required. However, using struc-
tures with sequential layout without interacting with unmanaged code is very inef-
ficient. If you are using structures for performance reasons, without the intent to
communicate with legacy code, you can explicitly declare a struct as auto layout
with the following code.
public struct MyStructure
The Myth About Foreach Loops
A common misconception with code optimization is that using a for loop instead
of a foreach loop will offer better performance. In actuality, this advice used to be
correct back when compilers were not intelligent enough to determine the logical
equality between a for and a foreach loop in like situations. This thought is based
on the assumption that an enumerator is instantiated inside a foreach loop to iter-
ate through the elements of a collection, which is not a factor anymore because of
processor speeds and compiler optimization. Using a foreach loop to iterate
through the elements of an array will make no substantial difference in perfor-
mance, if any at all.
To review, writing a for loop like the following code:
for (int index = 0; index < array.Length; index++)
// Do processing on array[index]
will perform the same as a foreach loop like the following code (assuming an array
of bytes for the sake of argument).
foreach (byte element in array)
// Do processing on element
There is one situation where a for loop might be more efficient than a foreach
loop, and that is when the size of the collection is a fixed value that you are aware
of when writing the code. Consider the following code.
for (int index = 0; index < 15; index++)