The Humble For()

In most C# is normal to use the fantastically easy foreach() construct to iterate a set. This comes with a hidden cost;

  1. An incrementor object is created for the duration of the loop and then destroyed, which is fine if you dont suffer from heap fragmentation, or are not aware that different C# .net frameworks have different GC implementations (XBox for instance).
  2. the incrementor cannot easily be used in an anonymous code block within the loop, as, by the time the code is executed, the incrementor may yield a different value to the one it had when the code block was constructed.

Reconsider our old friend for() which is faster to execute, doesn’t lead to heap allocations and doesn’t suffer from the anonymous code block problem.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s