FAQFAQ SearchSearch All Topics At A GlanceAll Topics At A Glance newpostsNew Posts UnansweredUnanswered Posts   RegisterRegister   ProfileProfile Log in to check your private messagesLog in to check your private messages Log inLog in
FeedBurner FeedFeedBurner RSS 2.0 Feed Request a New ForumRequest a New Forum


   ¤ C# Performance - Switch vs If-Then ¤

Author Message
mteric
Active Poster
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#?
Back to top
 
C# Performance - Switch vs If-Then Posted: Mon Jun 04, 2007 1:34 pm     C# Performance - Switch vs If-Then Reply with quote
Post new topic   Reply to topic    Back to the Programming and Software Development Chat Forum <--
Google
 

 


Powered by phpBB © 2001, 2005 phpBB Group