-2

what is faster

AnswerClass ansClass = obj as AnswerClass;
if(ansClass != null){
    //use ansClass directly
}

or

if(obj is AnswerClass ){
   AnswerClass ansClass = (AnswerClass) obj;
   //use ansClass now
}

In C#.net.

I have looked around but cannot find anything that answers this, does anybody here know?

I have edited to better explain the question I have, It is comparing 'as' then null check, then use, with 'is' then a direct Cast?

f1wade
  • 2,877
  • 6
  • 27
  • 43
  • 4
    There's very useful class (`System.Diagnostics.Stopwatch`) for profiling things like this. – Leri Oct 22 '12 at 10:50
  • 3
    If this is really the bottleneck for performance in your application, you've got deeper issues. – Damien_The_Unbeliever Oct 22 '12 at 10:50
  • You should read this : http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html – Ta Duy Anh Oct 22 '12 at 10:50
  • 1
    Try it. Run each in a loop (several million times around the loop), time them and find out for yourself. – Oded Oct 22 '12 at 10:50
  • 2
    why not `var answerStruct=obj as AnswerStruct; if (answerStruct!=null) {` no need for additional cast inside? – Bob Vale Oct 22 '12 at 10:53
  • Well you can Time it out and find which one is faster ! ! – V4Vendetta Oct 22 '12 at 10:53
  • @BobVale If `AnswerStruct` is really a reference type (like `class`, `interface`, `delegate` type, or array type), that's the nicest way in my opinion. But if `AnswerStruct` is a value type (like **`struct`** or `enum`), see my comment to dtb's answer. – Jeppe Stig Nielsen Oct 22 '12 at 11:40

5 Answers5

6

The as operator doesn't work with value types (structs), so if you have

struct SomeStruct { }

object obj = new SomeStruct();

then the only option to find out the type and unbox the value is

if (obj is SomeStruct)
{
    SomeStruct val = (SomeStruct)obj;
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 2
    Correct. He could say `var answer = obj as AnswerStruct?; if (answer.HasValue) { ... }` but that's slower according to [Performance surprise with “as” and nullable types](http://stackoverflow.com/questions/1583050/). – Jeppe Stig Nielsen Oct 22 '12 at 11:32
2

Both of the them are same, there is no difference (I hope its a class not a struct, in your question, otherwise it won't compile)

Suppose you have:

class Test
{
    public int MyProperty { get; set; }
    public int SomeOther { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        object obj = new Test();

        if (obj as Test != null)
        {
            Console.WriteLine("test1");
        }

        if (obj is Test)
        {
            Console.WriteLine("test2");
        }

    }

If you view the code in ILSpy.

private static void Main(string[] args)
{
    object obj = new Test();
    if (obj is Test)
    {
        Console.WriteLine("test1");
    }
    if (obj is Test)
    {
        Console.WriteLine("test2");
    }
}

Here is the IL from ildasm

.method private hidebysig static void Main(string[] args) cil managed

{
  .entrypoint
  // Code size       43 (0x2b)
  .maxstack  1
  .locals init ([0] object obj)
  IL_0000:  newobj     instance void ILTest.Test::.ctor()
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  isinst     ILTest.Test
  IL_000c:  brfalse.s  IL_0018
  IL_000e:  ldstr      "test1"
  IL_0013:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0018:  ldloc.0
  IL_0019:  isinst     ILTest.Test
  IL_001e:  brfalse.s  IL_002a
  IL_0020:  ldstr      "test2"
  IL_0025:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_002a:  ret
} // end of method Program::Main
Habib
  • 219,104
  • 29
  • 407
  • 436
  • It is also the same for a struct? – Kobi Oct 22 '12 at 11:12
  • @Kobi, I haven't tried it with struct,I believe I won't be able to use `!= null` with struct/value types. Also the keyword `as` will not work with value types – Habib Oct 22 '12 at 11:14
1

When you want to check if obj is an AnswerStruct, how on Earth can you go clearer than:

if(obj is AnswerStruct)

If you are so concerned about microoptimisations, the first thing you should do is use a non-managed language. This aside from the fact that there is actually nothing faster than this piece of code and that, as dtb wrote in his answer, sometimes this is the only variation that will work. Do not sacrifice clarity for a worthless gain in speed, specially when there is no gain at all.

Community
  • 1
  • 1
Gorpik
  • 10,940
  • 4
  • 36
  • 56
0

Assuming you meant to talk about classes

They're equivalent, as they compile down to the same bytecode.

The as operator simply calls the isinst operator, while the is operator calls isinst, and then checks for null, just like you did.

Yam Marcovic
  • 7,953
  • 1
  • 28
  • 38
0

These are the two ways but the same calling process both take the same time ( as operator calls the isinst operator and same with is operator calls isinst and both will check for null).

RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262