Re: if statements vs. switch
Re: if statements vs. switch
- Subject: Re: if statements vs. switch
- From: Michael George <email@hidden>
- Date: Wed, 4 Sep 2002 10:19:20 -0400
The switch is more efficient, however it is only applicable when the
object of the comparison is a constant.
On Wednesday, September 4, 2002, at 10:00 AM, Jeremy Dronfield wrote:
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.
-Michael George
Senior Engineer, Software Development
Aurora Video Systems, Inc.
_______________________________________________
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.