The speed of collections and For loops in C#

Some of the .NET training I’m doing started me wondering about speeds and things. So, I wrote some testing and turned up some interesting things…

First off, I tried comparing the speed of populating and reading from generic and normal collections. I found that Generics are much faster to populate as well as read from. I’d expected the latter (no type conversion needed), but not a better speed at population. I guess this is because the types can be checked at compile time. I tried this with both a value type (so there might be boxing/unboxing), and a reference type – each time the result was the same, non-generics took ten times as long as generics.

Populating a generic list is twice as fast if it has its capacity assigned. E.g.

List<SomeObj> myList = new List<SomeObj> ( 10000 );

Populating a non-generic list is actually slower if it has its capacity assigned. I have absolutely no idea why.

FOR Loops are slightly faster than FOREACH loops. However, the difference is piddling, so I’d actually recommend not worrying. Out of preference, I’ll use FOREACH, ‘cos it’s easier to read.

Looking at converting types (well, an integer in most of my tests) I found that:

  • AS is slightly faster than a cast
  • (cast) is much faster than System.Convert

It’s worth noting that if a conversion fails, AS will just return NULL, whereas a cast returns an exception. Raising an exception is slower than testing for null. Therefore, AS has a definite speed advantage, and hence why you shouldn’t handle expected exceptions using, um, exceptions. Instead, test something and then deal with the exception case. For example, you something like TryParse. (Actually, I should give that a whirl, see how long it takes.)E.g.

int w = 12;
Object o = w;

//fastest conversion and error handling
int x = o as int;
if( x == null) { };

//Okay speed, very slow error handling
try {
int y = (int) o;
} catch ( InvalidCastExpection e ) {}

//Don’t do this
try {
int y = System.Convert.ToInt32(o);
} catch ( InvalidCastExpection e ) {}

I’ll get back to you all about the TryParse thing.

Advertisements
The speed of collections and For loops in C#

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