In one of our projects we had a little performance problem, so we researched some stuff to get things faster.
Problem:
We have a XML File with a List<Base> and we wanted to generate Enterprise Architect Elements out of them.
So we needed to check if the Base element is of type: Class1, Class2,… to get all our attributes and some class specific functions called.
We used 200 elements and 15 derived classes and run through each test about 10 times,
here are the results on how to do this really fast:
Slowest:
public void test()
{
foreach (Base baseClass in baseList)
{
Class1 class1 = baseClass as Class1;
if (!object.Equals(class1, null))
{
class1.Create();
}
Class2 class2 = baseClass as Class2;
if (!object.Equals(class2, null))
{
class2.Create();
}
}
}
took about: 0.0001404 – 0.0001719 seconds
public void test()
{
foreach (Base baseClass in baseList)
{
if (baseclass is Class1)
{
((Class1)baseClass).Create();
}
…}
}
took about: 0.0001234 – 0.0001668 seconds
public void test()
{
foreach (Base baseClass in baseList)
{
switch (baseClass.GetType().Name)
{
case (“Class1”):
((Class1)baseClass).Create();
break;
…
}
}
took about: 0.0000843 – 0.0001367 seconds
And the winner is:
1. Create an interface:
public interface IBase
{
void Create();
}
2. implement the interface in Base, Class1, Class2,….
public class Class1: Base, IBase
{
public new void Create()
{
}
}
3. and:
public void test()
{
foreach (IBase baseClass in baseList)
{
baseClass.Create();}
}
took about: 0.0000571 – 0.0000652 seconds
Trackbacks/Pingbacks