Objective-C中的消息发送成本 [英] Cost of message dispatch in Objective-C

查看:71
本文介绍了Objective-C中的消息发送成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道在各种情况下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.

我当前的项目是我有一个带有实例变量的类:offsetX和offsetY。我经常想要绝对偏移量,目前我在这个地方都有这行代码: -

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);

现在如果这是C ++,我会创建一个返回absOffset值的内联函数。即使在Java / C#中,我也可以将这样的函数定义为final / sealed,并且非常确定它将被内联。

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.

目标-C将是: -

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];

现在,编译器能够内联吗?我假设它至少能够将它修复为直接函数调用并避免动态消息调度(我假设)objective-c必须使用因为它的类型系统。

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.

另外,一般来说,客观C中的消息发送费用是多少?通过'id'和指向具体类的指针调用它有什么不同?

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?

推荐答案

目标C消息非常快。速度可比到C ++虚拟方法调用,虽然不是那么快。避免消息传递肯定是过早优化。您可能不希望在内部循环中执行大量操作,但您选择的算法和其他因素将对代码的速度有更大的影响。如果它太慢,请使用分析器并从那里开始。

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.

这篇关于Objective-C中的消息发送成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆