C# Performance#2 – as vs () 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; // 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;