Home > C# > C# Performance#2 – as vs () operator

C# Performance#2 – as vs () operator

Like in the previous example also in this I’ll make a small experiment with C#. This time I’ll take a closer look at two operators and a programming method. I’ll take a look on as/is and () operator.

Imagine a list of objects like List<object> and a custom class for example MySimpleClass. Before the generic programming came, programmers used to write a list which contained a couple of items (such list is known as collection). In such list we can put as many objects of different types as we can (of course there is a item limit). When we will get an item we just can use the get method (indexer) and then cast to specific type. When the collection has many different type items then we should write a long if maby with some is conditions. Happily this is a rare situation, because such kind of lists mostly contains only one type of object. OK, but also with this, the list contains only Object types, and our item must be casted to MySimpleClass. In this situation the casting is required when we will get our properties from MySimpleClass.

We can achieve this by casting an object using () or as operator. Maby this will show a simple example

object ourObject = list[1]; // get the first item from the list

MySimpleClass myItem = (MySimpleClass)ourObject; // this is casting using () operator

In code is operator checks if the ourObject is an MySimleClass type, and as operator casts to a specified type. The advantage of the is operator is that this operator never throws casting exception, but only null when the object is not the of the casted type.

Let’s make an experimet. In this experiment I’ll compare casting object to a specified type using the as operator or (). Like last time, I wrote a simple program with two methods. First method is using as operator and the second () operator. I ran the program in a big loop and one object. Then in each iteration I casted to the MySimpleClass object. The results shocked me, because using as was three times faster than ().

 

Using as Cast by ()
2388,8 ms 9551,1 ms

 

It’s a lot of time, and the difference was only in one, maby half line of code:

First method: MySimpleClass myClass = item as MySimpleClass;

Second method: MySimpleClass myClass = (MySimpleClass)item;

  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: