Will the C# compiler optimize this?

A

Andreas Mueller

Hi All,

I recently came across a code snippet similar to the one below generated
by a code generator. I asked myself, if the compiler will optimize this
or if the program will do the actual (needless) cast at runtime:

class SomeGeneratedClass
{
public object Foo()
{
return null;//returns something sensible in real live
}
}
class OtherGeneratedClass
{
public void void Xox()
{
object o = (object)m_.Foo();//needless cast!
//will the compiler optimize this?
}
private SomeGeneratedClassm_ = new SomeGeneratedClass();
}


If it does optimize it, will it also optimize this situation?

class Xox : ICloneable
{
// hidden interface implementation
object ICloneable.Clone(){ return null; }
}

class Other
{
public void Foo()
{
Xox x = new Xox();
object o = ((ICloneable)x).Clone();//How about this?
// will it do a cast to ICloneable at runtime?
}
}

Thank you very much in advance,
Andy
 
C

Chad Myers

Andreas said:
Hi All,

I recently came across a code snippet similar to the one below generated
by a code generator. I asked myself, if the compiler will optimize this
or if the program will do the actual (needless) cast at runtime:

class SomeGeneratedClass
{
public object Foo()
{
return null;//returns something sensible in real live
}
}
class OtherGeneratedClass
{
public void void Xox()
{
object o = (object)m_.Foo();//needless cast!
//will the compiler optimize this?
}
private SomeGeneratedClassm_ = new SomeGeneratedClass();
}


If it does optimize it, will it also optimize this situation?

class Xox : ICloneable
{
// hidden interface implementation
object ICloneable.Clone(){ return null; }
}

class Other
{
public void Foo()
{
Xox x = new Xox();
object o = ((ICloneable)x).Clone();//How about this?
// will it do a cast to ICloneable at runtime?
}
}

Thank you very much in advance,
Andy

First things first, none of the .NET compilers really do any optimizing.
Only the JIT in the Runtime does significant optimizing.

Second, from what I understand, casts aren't a big deal, so I'm not sure
why you're so concerned about casting.

In general, in .NET, you shouldn't be worried about simple language
constructs and performance. In modern languages, when you try to
optimize the code yourself, you really only hurt yourself because it'll
only confuse the optimizer and probably result in worse performance.

Just code simply and naturally and the optimizer will work very, very well.

-c
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top