John Baro said:
What are the cost of **is**, **as** as compared to a straight cast via
(type)
Personally I would think **as** would be most costly followed by **is**
?closely? followed by a straight cast.
No - is and as basically have the same cost (assuming you then do a
test for nullity in the as case), as they both use the "isinst" IL,
just with different results. Here's a sample piece of benchmark code:
using System;
public class CastCost
{
static int iterations=1000000000;
static int count;
static object testObject = "hello";
public static void Init (string[] args)
{
if (args.Length >= 1)
iterations = Int32.Parse(args[0]);
}
[Benchmark]
public static void Is()
{
int localCount=0;
for (int i=iterations; i > 0; i--)
{
if (testObject is string)
{
localCount++;
}
}
count = localCount;
}
[Benchmark]
public static void As()
{
int localCount=0;
for (int i=iterations; i > 0; i--)
{
if (testObject as string != null)
{
localCount++;
}
}
count = localCount;
}
[Benchmark]
public static void Cast()
{
int localCount=0;
for (int i=iterations; i > 0; i--)
{
string x = (string)testObject;
localCount++;
}
count = localCount;
}
public static void Check()
{
if (count != iterations)
throw new Exception (String.Format("{0} != {1}", count,
iterations));
}
}
See
http://www.pobox.com/~skeet/csharp/benchmark.html for how to run
the code. Here are my results:
Benchmarking type CastCost
Run #1
Is 00:00:04.7656250
As 00:00:04.7031250
Cast 00:00:05.5156250
Run #2
Is 00:00:04.7968750
As 00:00:04.7031250
Cast 00:00:05.5312500
Now, looking at the IL for As() and Is(), you'll see something
interesting: they're *exactly* the same.