How much overhead does a msg_send call incur?

岁酱吖の 提交于 2019-12-08 07:19:07

问题


I'm attempting to piece together and run a list of tasks put together by a user. These task lists can be hundreds or thousand of items long.

From what I know, the easiest and most obvious way would be to build an array and then iterate through them:

NSArray *arrayOfTasks = .... init and fill with thousands of tasks

for (id *eachTask in arrayOfTasks)
{
  if ( eachTask && [eachTask respondsToSelector:@selector(execute)] ) [eachTask execute];
}

For a desktop, this may be no problem, but for an iphone or ipad, this may be a problem. Is this a good way to go about it, or is there a faster way to accomplish the same thing?

The reason why I'm asking about how much overhead a msg_send occurs is that I could also do a straight C implementation as well. For example, I could put together a linked list and use a block to handle the next task. Will I gain anything from that or is it really more trouble than its worth?


回答1:


I assume you're talking about objc_msgSend, in which case, Bill Bumgarner has an excellent 4 Part Series that is worth a read.

In general though, I would recommend simply using Obj-C. This is what all apps for the iDevices use, including Apple, and hundreds of items is not going to kill the device.




回答2:


What rynmrtn said...

Unless your -execute methods were exceedingly simplistic -- incrementing / testing a small handful of scalar values -- then it is unlikely that objc_msgSend() will even show up as a % of your program's CPU time.

Measure first, optimize after.

Your code does raise a question; why are you putting things into the arrayOfTasks that might not be able to execute. Assuming everything in your arrayOfTasks is a subclass of your making, you could add an execute method and not do the responds test. If you have a hierarchy of collection classes, you could use categories to add the methods -- just put a prefix on 'em to be safe (i.e. pxl_execute or something).




回答3:


Here is a nice benchmark comparison of common operations, including objc_msgSend. In general, you shouldn't worry about objc_msgSend performance, even on the iPhone. Message sending will always be slower than a straight C function call, but on a modern processor (remember, the iPhone processor is still about 500 mhz), the difference is trivial most of the time. If profiling shows that a lot of time is being used in objc_msgSend, then it might be worth using straight C functions instead of Objective-C methods.

For clarity, you can use -[NSArray makeObjectsPerformSelector:] or (on Mac) enumerateObjectsUsingBlock: instead of iterating through the objects, but I don't think it should make much performance difference.



来源:https://stackoverflow.com/questions/2962466/how-much-overhead-does-a-msg-send-call-incur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!