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?
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
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With