Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Is there a performance hit when I cast an object to it's type?

 

Such as:

object o = "Hello, world!";
string s = (string)o;

 

Does the code compare types first?

"For every complex problem, there is a solution that is simple, neat, and wrong." - H. L. Mencken
  • *Experts*
Posted

When you cast to a type from object (an unknown type at compile time) there will be a slight performance cost. The thing is, you MUST cast it if you want to use it as that type so it doesn't matter too much :)

 

If you cast a string to a string (I've seen it done!) then, I would guess, the compiler would ignore the cast:

string s = "hello";

string s2 = (string)s;

 

That would be true for any object being cast to its native type.

 

On a similar note, if you have a class hierarchy and you cast to a lower-level type, there shouldn't be a performance hit - the compiler will know how to convert it internally and the compiled code will call directly into whatever method/property you referenced. For example:

public class ClassA
{
   public string Test()
   {
       return "hello";
   }
...
}

public class ClassB : ClassA
{
   public string Test2()
   {
       return "world";
   }
...
}

ClassB b = new ClassB();
string s = ((ClassA)b).Test();

 

Of course, in the above example, you don't have to cast variable b as ClassA - the compiler will let you call Test directly. But for the purposes of asking about performance, casting as the base type (ClassA) on a variable declared as a "higher" type (ClassB) should have no performance impact.

 

-ner

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...