Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient run-time type checking

I have hierarchy of classes like follows (in fact I have more than 3 derived types):

class A {};
class B : A  {};
class C : B  {};
class D : A  {};

Instances of these classes are stored in List<A> collections. Sometimes collections are quite big (thousands or even tens of thousands of objects).

In my code I frequently need to perform some actions depending on the exact type of the objects. Something like this:

List<A> collection = ...
foreach (A obj in collection)
{
    if (obj is C)
        something(obj as C);
    else if (obj is B)
        somethingElse(obj as B);
    ....
}

As you see, the code performs many checks for type of the object and casts. For collections with many elements performance of the code is not that great.

What would you recommend to speed up run time type checks in my case?

like image 608
Bobrovsky Avatar asked Jun 05 '11 09:06

Bobrovsky


2 Answers

It sounds to me like you should move the "something" into a virtual method on A, then each of B, C and D can override it as they need (which may just mean calling an external method - they don't need to do the work themselves) - or not override as they need.

Then this becomes:

foreach (A obj in collection)
{
    obj.DoSomething();
}

i.e.

class A {
    public virtual void DoSomething() {...}
}
class B : A   {
    public override void DoSomething() {...}
}

etc

like image 86
Marc Gravell Avatar answered Oct 24 '22 09:10

Marc Gravell


Make the functionality implemented in the function "something" a behaviour/method of Class A and then redefine it in child classes as applicable (make sure the method is defined as virtual).

In this case you can straight away call:

List<A> collection = ...
foreach (A obj in collection)
{
  obj.something()
}
like image 4
Chandu Avatar answered Oct 24 '22 09:10

Chandu