JonYates's Random Writings
if vs. Switch
No tags have been created or used yet.
May 2006 (1)
May 2004 (1)
March 2004 (2)
I think a switch is more about code readability than functionality. I use it whenever I have more than one elseif to improve the readability of my code.
That's all a switch is good for!!!
March 23, 2004 1:01 PM
Of course, the only answer is "it depends on the situation".
A switch is just like what it sounds -- imagine a knob with five positions, you switch it to one of them. An "if" is just like what it sounds -- you have a condition, you evaluate its truthfulness, you do the appropriate consequences.
Which you choose depends on which situation you find yourself in.
A third option often overlooked is to have table-driven logic rather than statement-driven logic. Often See my article here:
March 23, 2004 2:19 PM
Suman Chakrabarti said:
I remember hearing once that in VB6-- if statements were faster than select statements but select statements were for easier readability.
I doubt there is a performance difference in managed code, but they certainly are a plus.
Maybe one of the benefits is the fact that you can fall through several cases whereas with an if..else you break immediately. For example:
Console.WriteLine("I'm an Administrator");
Console.WriteLine("I have Moderator rights");
Console.WriteLine("I'm only a user");
That's probably the only benefit other than readability
March 23, 2004 3:48 PM
Someone posted a couple of days ago about this very subject. Can't remember who, but the upshot was that the switch was faster than the ifs.
The surmise was that the jitter optimised the heck out of the switch.
Sorry I can't remember who posted it. It was in response to something on Darren Neimke's blog.
March 23, 2004 5:20 PM
April 9, 2005 11:56 PM
JonYates's Randon writings or JobYates's Mindless Writings ... y wasting urs and others time doing so?
May 2, 2006 4:21 PM
Fascinating feedback, do you mind expanding on what you feel was a waste of time?
May 3, 2006 6:15 AM