mteric
Active Poster

Joined: 23 Aug 2006
Posts: 116
Location: Montana, USA
|
Coming from the C/C++ world, I've always used switch statements sparingly because of the slight performance hit versus using if-then statements. But after running several quick tests (like the quick-and-dirty one below), it seems that in C#, the Visual Studio compiler is able to optimize the switches so that they're faster than using if-then statements. | Code: | int iBegin = Environment.TickCount; for (int x = 0; x < 1000000000; ++x) { int i = 1; switch (i) { case 0: break; case 1: break; default: break; } } int iEnd = Environment.TickCount; int iTotal = iEnd - iBegin; Console.WriteLine("Switch took " + iTotal.ToString()); iBegin = Environment.TickCount; for (int x = 0; x < 1000000000; ++x) { int i = 1; if (i == 0) { } else if (i == 1) { } else
{ } } iEnd = Environment.TickCount; iTotal = iEnd - iBegin; Console.WriteLine("If-Then took " + iTotal.ToString()); | Output on my machine: Switch took 4828
If-Then took 8016
Has anyone else had any negative results from using switches in C#?
|
|