Tuesday, September 23, 2008

Prefix vs As Casting : Which is faster?

.Net Provides two ways to Cast an object, namely, Prefix Casting and "as casting". "As Casting" provides an additional type which results in a null value to be returned in case of casting error. On other hand, Prefix casting would throw an exception in that scenario.

But which is faster ? Well, it seems strange that even though "as-casting" provides an additional checking it seems faster than the prefix. Following sample code demonstrate the same.


ArrayList d = new ArrayList();
for (int i = 0; i < 67108864; i++)
{
d.Add(new Class1(i));
}
Class1 obj1;
DateTime dtAS = DateTime.Now;
for (int i = 0; i < 67108864; i++)
{
obj1 = d[i] as Class1;
}
Console.WriteLine((DateTime.Now - dtAS).Milliseconds.ToString());
Class1 obj2; DateTime dtN = DateTime.Now;
for (int i = 0; i < 67108864; i++)
{
obj2 = (Class1)d[i] ;
}
Console.WriteLine((DateTime.Now - dtN).Milliseconds.ToString());



If you look into the IL code for same, you would notice that "as casting" uses isinst IL command while prefix casting uses "castclass" method.

But if you have a look at how MSDN has defined isinst command, it can lead to think why in the earlier code, as casting works faster.

Here is a snippet from MSDN about isinst

Tests whether an object reference (type O) is an instance of a particular class.

"If the class of the object on the top of the stack implements class (if class is an interface) or is a derived class of class (if class is a regular class) then it is cast to type class and the result is pushed on the stack, exactly as though Castclass had been called. Otherwise, a null reference is pushed on the stack. If the object reference itself is a null reference, then isinst likewise returns a null reference."

Now if object is casted exactly as though CastClass after validation, then how is it that its faster ?

anyone has any suggestions ?