I’ve been led to believe that casting can, in certain circumstances, become a measurable hindrance on performance. This may be moreso the case when we start dealing with incoherent webs of nasty exception throwing\catching.
Given that I wish to create more correct heuristics when it comes to programming, I’ve been prompted to ask this question to the .NET gurus out there: Is interface casting faster than class casting?
To give a code example, let’s say this exists:
public interface IEntity { IParent DaddyMommy { get; } }
public interface IParent : IEntity { }
public class Parent : Entity, IParent { }
public class Entity : IEntity
{
public IParent DaddyMommy { get; protected set; }
public IParent AdamEve_Interfaces
{
get
{
IEntity e = this;
while (e.DaddyMommy != null)
e = e.DaddyMommy as IEntity;
return e as IParent;
}
}
public Parent AdamEve_Classes
{
get
{
Entity e = this;
while (e.DaddyMommy != null)
e = e.DaddyMommy as Entity;
return e as Parent;
}
}
}
So, is AdamEve_Interfaces faster than AdamEve_Classes? If so, by how much? And, if you know the answer, why?
Take a look at here:
http://thatstoday.com/robbanp/blog/6/25/csharp-performance–cast-vs-interface
And, yes, you seem to be right.
Edit Well, it seems that I was wrong. And like my “patrício” Martinho Fernandes commented bellow, the above link is completely bogus (but I’ll keep it here, for the sake of honest editing).
I do have some spare time nowadays, so I’ve written a simple performance measuring code:
And the result is:
I really used to think that an interface would be faster for
classtypes, and slower forstruct(since boxing/unboxing is involved in the latter), but that is not the case: a concrete class/struct reference is always faster, it seems.Also, to whom it may concern: I believe that performance is not a good criteria for deciding if an interface should or should not be used. The difference is, like others said here, negligible.