if statements vs. switch
if statements vs. switch
- Subject: if statements vs. switch
- From: Jeremy Dronfield <email@hidden>
- Date: Wed, 4 Sep 2002 15:00:12 +0100
A C question really, and a matter of interest rather than a problem.
From the point of view of speed and/or efficiency, what are the relative
merits of a chain of IF statements versus a switch? Take the following
as an example:
As ifs:
if ([prefs integerForKey:@"ControlsDisplaySide"] == 0) [myWindow
setFrameTopLeftPoint:topLeft];
if ([prefs integerForKey:@"ControlsDisplaySide"] == 1) [myWindow
setFrameTopLeftPoint:bottomLeft];
if ([prefs integerForKey:@"ControlsDisplaySide"] == 2) [myWindow
setFrameTopLeftPoint:topRight];
if ([prefs integerForKey:@"ControlsDisplaySide"] == 3) [myWindow
setFrameTopLeftPoint:bottomRight];
As switch:
switch ([prefs integerForKey:@"ControlsDisplaySide"]) {
case 0:
[myWindow setFrameTopLeftPoint:topLeft];
break;
case 1:
[myWindow setFrameTopLeftPoint:bottomLeft];
break;
case 2:
[myWindow setFrameTopLeftPoint:topRight];
break;
case 3:
[myWindow setFrameTopLeftPoint:bottomRight];
break;
}
Does the switch only read the "prefs" value once, or is this appearance
misleading? Will one approach compile more efficiently (i.e. more
compactly) than the other? Will changing the second thru' fourth "ifs"
into "else ifs" actually make for cleaner running (I presume it would)?
I suppose one could tidy up the ifs further by putting the prefs value
into an int and using that for comparison, but what I'd really like to
know is whether the switch is generally better. My "Introduction to C"
just says vaguely that it's more convenient.
-Jeremy
========================================
email@hidden // email@hidden
The Alchemy Pages:
- fractious fiction at
http://freespace.virgin.net/jeremy.dronfield
========================================
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.