Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

iphone - Cost of message dispatch in Objective-C

I'm curious to know about the cost of message dispatch in Objective-C in various situations. Particularly I want to guide my choice of program design so I'm not tempted to prematurely optimize by avoiding message dispatches when they would make for a better design.

A case in my current project is that I have a class with instance variables: offsetX and offsetY. I often want the absolute offset and at the moment I have this line of code all over the place:-

int absOffset = ((offsetX < 0.0) ? -offsetX : offsetX) + 
                 ((offsetY < 0.0) ? -offsetY : offsetY);

Now if this was C++ I would create an inline function that returned the value for absOffset. Even in Java/C# I could define such a function as final/sealed and be pretty sure it would be inlined.

The objective-C would be:-

-(int)absOffset {
    return ((offsetX < 0.0) ? -offsetX : offsetX) + 
            ((offsetY < 0.0) ? -offsetY : offsetY);
}

and I would call it like so:-

int ao = [self absOffset];

Now, is the compiler able to inline that? I assume it is able at least fix it to a direct function call and avoid the dynamic message dispatch that (I assume) objective-c must use because of it's type system.

Also, in general, how much does message dispatch cost in objective-C? Does it differ when calling through an 'id' versus a pointer to a concrete class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Objective C messages are very fast. The speed is comparable to C++ virtual method calls, although not quite as fast. Avoiding message passing is definitely premature optimization. You might not want to do a lot of it in an inner loop, but the algorithms you choose and other factors will have a much bigger factor on how fast your code is. If it is too slow, use a profiler and go from there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...