Ok, I read in MSDN magazine that to optimize performance you should be familiar with how high level code gets compiled into MSIL and what the potential impacts are. Having over 4000 classes in .NET gives developers many ways to do the same thing, but some ways can be more efficient than others, take the following trivial test cases:
Test 1
private void SlowCode(string x)
{
Random rnd = new Random();
int number = 0;
for (int i = 0; i < 5000000 ; i++)
{
// here is the inefficient way
if(x.Equals("Hello world"))
{
number = rnd.Next();
}
}
}
Test 2
private void BestPracticesCode(string x)
{
Random rnd = new Random();
int number = 0;
for (int j = 0; j < 5000000 ; j++)
{
// here is the best practices way
if(x != null && x == "Hello World")
{
number = rnd.Next();
}
}
}
Ultimately the 2 tests do the same thing, i.e. check a value and do some work when a condition is true, and here are the results in milliseconds after executing both tests 10 times:
SlowCode():0.511
BestPracticesCode():0.25
SlowCode():0.461
BestPracticesCode():0.25
SlowCode():0.471
BestPracticesCode():0.25
SlowCode():0.471
BestPracticesCode():0.25
SlowCode():0.471
BestPracticesCode():0.25
SlowCode():0.461
BestPracticesCode():0.25
SlowCode():0.471
BestPracticesCode():0.24
SlowCode():0.471
BestPracticesCode():0.25
SlowCode():0.471
BestPracticesCode():0.24
SlowCode():0.471
BestPracticesCode():0.24
So my question is this: is there a more effecient way to write this code:
if (stateManager.CurrentState().Equals(typeof(FirstStep))
CurrentState() is a method that has a return type of System.Type and we are checking it to see if it is the same type as the FirstStep class. FirstStep is also a sub class of StateBase.
Ultimately what I need to do is a switch on the result of CurrentState(). For each case in the switch I need to execute seperate logic.