I just want to know what the difference between all the conditional statements in objective-c and which one is faster and lighter.
I just want to know what the difference between all the conditional statements in
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The language-agnostic version (mostly, obviously this doesn’t count for declarative languages or other weird ones):
When I was taught programming (quite a while ago, I’ll freely admit), a language consisted of three ways of executing instructions:
The
ifandcasestatements are both variants on selection.Ifis used to select one of two different options based on a condition (using pseudo-code):keeping in mind that the
elsemay not be needed in which case it’s effectivelyelse do nothing. Also remember that option 1 or 2 may also consist of any of the statement types, including moreifstatements (called nesting).Caseis slightly different – it’s generally meant for more than two choices like when you want to do different things based on a character:Note that you can use
casefor two options (or even one) but it’s a bit like killing a fly with a thermonuclear warhead.Whileis not a selection variant but an iteration one. It belongs with the likes offor,repeat,untiland a host of other possibilities.As to which is fastest, it doesn’t matter in the vast majority of cases. The compiler writers know far more than we mortal folk how to get the last bit of performance out of their code. You either trust them to do their job right or you hand-code it in assembly yourself (I’d prefer the former).
You’ll get far more performance by concentrating on the macro view rather than the minor things. That includes selection of appropriate algorithms, profiling, and targeting of hot spots. It does little good to find something that take five minutes each month and get that running in two minutes. Better to get a smaller improvement in something happening every minute.
The language constructs like
if,while,caseand so on will already be as fast as they can be since they’re used heavily and are relative simple. You should be first writing your code for readability and only worrying about performance when it becomes an issue (see YAGNI).Even if you found that using
if/gotocombinations instead ofcaseallowed you to run a bit faster, the resulting morass of source code would be harder to maintain down the track.