Re: Code optimization
Re: Code optimization
- Subject: Re: Code optimization
- From: Nicko van Someren <email@hidden>
- Date: Fri, 2 Jan 2004 12:34:19 +0000
On 2 Jan 2004, at 11:13, Denis Vaillant wrote:
Hi everybody and happy new year ;)
I have a question regarding code optimization : is it faster to use
"case"
structure than "if" and "else if" ?
Short answer: yes.
Longer answer: In most compilers, and certainly in GCC, switch(...) {
case ...: ...} is more efficient when the cases are densely specified
(e.g. you specify actions for every value between 1 and 10) as in this
case it uses a jump table rather than repeatedly doing a comparison and
jumping over the next block. If the cases are fairly sparse (e.g. you
have a cases for 6, 20, 42, 1001 etc.) then the compiler will make code
that looks pretty much like a sequence of if... else if... statements.
Note also that when it comes to coding in Objective C, should you end
up doing something like:
if ([obj getType] == 1) {
...
} else if ([obj getType] == 4) {
...
} else if ([obj getType] == 6) {
...
} else if ([obj getType] == 13) {
...
}
You would be much better off to say:
type = [obj getType];
if (type == 1) {
...
} else if (type == 4) {
...
} else if (type == 6) {
...
} else if (type == 13) {
...
}
This is because the compiler can't know in advance that the getType
message isn't going to return something different every time or have
some side effect (imagine the message was [obj nextThingy] or [obj
incrementFoo]) , so if you wrote for the message to be sent several
times it will send it several times, with the corresponding overheads.
If you use a switch () { case...:...} construction the generated code
will always be more like the later.
Cheers,
Nicko
_______________________________________________
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.