iamnp
iamnp

Reputation: 508

.NET 4, C++, how if...else and switch() affect on performance

Now in my app I am using this structure

if (e->UserState->Equals(1)) {} //stuff 1
else if (e->UserState->Equals(2)) {} //stuff 2
... // e - EventArgs of .NET 4 WebClient class

Should I better define

int n = (int)e->UserState;

And use switch()

switch(n)
{
  case 1:
  //stuff 1
  break;

  case 2:
  //stuff 2
  break;
}

Will it affect somehow on performance? (about 15 variants of e->UserState)

Upvotes: 0

Views: 94

Answers (3)

Marek R
Marek R

Reputation: 38092

Switch case will be faster (in this case) since compiler can do lots of tricks to make it faster, like table of jumps where value is used as a index to that table or binary search.
Note that if conditions in 'if's contains only variables and constants, compiler may do same tricks, but if you are calling some functions/methods inside conditions compiler have to do each check sequentially to keep side effects which may accrue inside this functions.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460238

Performance is not the key factor here (since it's negligibly) but readability. So etiher use switch or even a method:

public static void Stuff(UserState state)
{
    // do your stuff here ...
}

now you can use this (assuming UserState is an existing enum):

UserState state = (UserState)(int)e;
Stuff(state);

Upvotes: 0

Karthik T
Karthik T

Reputation: 31952

(about 15 variants of e->UserState)

I would write it in switch form purely for readability purposes! As for performance, you can check with profiling, but I doubt the difference if any would be statistically significant.

Upvotes: 3

Related Questions