Reducing objc_msgSend and retain/release calls [closed] - objective-c

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
The performance overhead of calling methods/properties in Objective-C is killing the performance of my iOS app; the Xcode profiler (aka, Instruments) attributes 70% of the latency to objc_msgSend, _retain, and _release.
In my code, so far, I make about 1100 calls to my XROpenGL class's instance method renderSprite(XRSprite) which is an overloaded method of renderSprite(XRSprite,int,int,int) which in turn invokes no less than five other methods, many of which access properties from XRSprite. As you can imagine, there's ALOT of messages being sent around.
Do I have any options apart from rewriting the critical sections of the code in C++?

Is that 6,600 calls per frame? I'll assume so for the sake of discussion, at 60 FPS for a total call count of 396,000 just for your explicit method calls. If you assume the pessimistic case, objc_msgSend's overhead (versus a C function call) is still only O(100) cycles. So on a modern iDevice you're looking at ~4% of your CPU time, very roughly. Not a huge deal. You might get a retain or two and corresponding releases for each call, but retain/release are relatively fast so we'd again be talking single-digit percentages. "Runtime overhead" of this nature of up to ~10% isn't considered egregious, generally, though it's not optimal.
So, the questions I have for you are:
Can you post your code?
Can you post more detailed profile information (e.g the exact breakdown between the various top 10 methods, as well as perhaps callstacks for the major ones)?
Are you sure the time is actually spent in objc_msgSend et al, and not merely in its children?
How many calls are you really making? As in measured, not assumed.
Can you use ivars instead of #properties, to remove some of the method calls?
Along those lines, are you caching the properties you do access when using them multiple times in one method?
Can you refactor to reduce the number of method calls, and/or use vanilla C functions for some things?
Obviously yes, you can rewrite key code in C++. But for mid-level drawing code you shouldn't have to; C++ is usually left to low-level constructs like vectors and quaternions and other such primitives.

Related

How threads are expressed in Objective-C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have read a lot of topics about the atomic and nonatomic attributes in Objective-C, and I understand that atomic means thread safe and therefore nonatomic is faster. But the main problem is that I don't understand what are threads at all and how they are being expressed in the code. Are they kind of methods? And I also noticed that most of the properties are nonatomic, why is that? I saw that threads may access setter or getter of a property simultaneously, how is this possible and how is this being expressed in the runtime? Also as a newbie programmer should I prefer atomic or nonatomic?
I have searched in a lot of questions regarding this but none has actually answered my question.
As Martin points out, people generally don't rely upon the atomic qualifier because that does not (generally) ensure thread-safety. The critical observation is that one must properly synchronize changes to variables as discussed in the Synchronization section of that Threading Programming Guide that Martin pointed you to.
So, in answer to your question, you probably should generally employ nonatomic (it's a little faster than atomic), but then determine which of the various synchronization techniques (serial queue, NSLock, NSRecursiveLock, #synchronized, etc.) as part of your broader thread-safe system design. In some cases, atomic might be part of that solution (as the Synchronization - Atomic Operations section of the Threading Programming Guide points out that atomic operations are "a simple form of synchronization that work on simple data types"), but as you're often dealing with objects, not simple data types, then atomic is likely to be insufficient.
As an aside, if you're diving into multi-threaded code for the first time, I might also suggest that you check out the Concurrency Programming Guide which talks about a slightly easier way to write multithreaded code without needing to get into the weeds of NSThread. You can either use dispatch queues (Grand Central Dispatch) and operation queues (NSOperationQueue).
Some additional references:
WWDC 2012 video Building Concurrent User Interfaces on iOS shows a practical example of operation queues;
WWDC 2012 video Asynchronous Design Patterns with Blocks, GCD, and XPC gives a bit of background on common asynchronous design patterns using Grand Central Dispatch (and XPC).
There are lots of other WWDC videos on the topic, but those might be two good ones to start with.
what are threads at all and how they are being expressed in the code.
Seriously, this is a big topic. So here are some thought and a specific answer to last question.
Actually, not all programs need concurrency, so I'd say if you haven't found a requirement for it in your application, you're free to relax. Then it won't matter if your properties are atomic or not.
Also as a newbie programmer should I prefer atomic or nonatomic?
As a newbie programmer, I'd say leave them as default. If they are fully synthesized, compiler will honestly synthesize an atomic getter and setter for you. There's nothing wrong with that, and certainly you shouldn't "try to make them faster" until you profiled the application and found that to be an issue.
If you provide methods for your properties yourself, your properties will actually be nonatomic, but I'm not sure marking them as such is worth the effort. Try to do that in code that is likely to be re-used by other people.
In some cases the compiler forces you to declare that the properties are nonatomic (when you pair a custom setter with synthesized getter or vice-versa). Well, in those cases go ahead and do that.

Can blocks replace delegate pattern via protocols in Objective C? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am an average iOS developer. The first design pattern that I saw heavily being used was Delegation pattern which was mostly being used for callback functionality.
Now that blocks are there in Objective C and I am seeing more and more libraries heavily using them and avoiding delegates, I am wondering, are blocks permanent replacement for delegate pattern using protocols ?
I recently used MKNetworkKit in a project, I created a wrapper class on top of it, the library is block based so all my code that would encapsulate a call to one of there block based code turned ot to be another block based code.
I found that it was very convenient initially, but was difficult to debug and modify as the code looked complex (callback inside callback inside callback!)
Any tips on when to use what and certain best practices ?
Delegates and blocks are both used for something to "call back" the result, usually to the thing that created it. There are some differences:
Using a delegate protocol, the method names you must implement to receive the callback are fixed. That means, if you need to receive callbacks from multiple possible actions using the same delegate protocol, you must somehow distinguish them. With blocks, there are no fixed names; you simply pass a block object with a particular signature. You can pass different block objects to different actions.
Delegate protocols often (but not always) contain more than one callback method, e.g. a "success" and a "failure" callback. Each block can only serve as one callback. Many libraries try to "combine" multiple delegate callbacks into a single block callback, by using multiple arguments, e.g. the block has two arguments (result, error), where if "error" is nil it corresponds to the original "success" callback, with "result" being the data; and if "error" is not nil, it corresponds to the original "failure" callback. Another option would be to give multiple blocks separately to the action (e.g. it has a "success block" property, and "failure block" property, which you can set). This is more general, and will work as a one-to-one replacement of a delegate protocol with any number of methods.
Memory management: Delegates are usually weakly-referenced, since the delegate is usually a "parent" object that owns the delegator. However, blocks are strongly referenced, since blocks are one-use things that are not needed anymore once passed to the delegator. However, if you think about it, it is not really different. With delegates, typically the delegate method will perform some action on itself (the parent object). With blocks, in order to do this, the block would need a reference to the "parent". It is then this reference that needs to be a weak reference, to emulate the memory management of the delegate pattern. With blocks, the parent object code has more control over how the delegate will reference it, because it sets up the block.
In conclusion, it is possible to systematically convert any API using a delegate protocol into one that uses blocks, with what I described above -- for each delegate method, add one block property on the delegator.
Protocols and the designated delegate objects they talk to are quite different than block-based code, which is usually used to encapsulating a task and/or shipping it off to GCD.
I do see one place in the Apple's Block documentation that appears to match some of the functionality that delegates provide:
Blocks are particularly useful as a callback because the block carries
both the code to be executed on callback and the data needed during
that execution.

Pros and cons of exception usage in iOS/ObjectiveC [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I read Apple's recommendation on exception usage and NSError usage:
Also, I read several similar stack overflow questions which discuss whether to use or not exception.
Exception Handeling in iOS
Using exceptions in Objective-C
Objective-C Exceptions
I am trying to figure out pros and cons of usage exception as error notification/handling method in iOS (Frankly, I am no satisfied with Apple's sentence (it says what to do, but it doesn't say why we should do it):
You should reserve the use of exceptions for programming or
unexpected runtime errors such as out-of-bounds collection access,
attempts to mutate immutable objects, sending an invalid message, and
losing the connection to the window server. You usually take care of
these sorts of errors with exceptions when an application is being
created rather than at runtime.
Exception usage pros:
It doesn't require to modify all intermediate code between error generating code and error handling code
It doesn't pollute arguments and return values for methods
Cons:
For all manually managed memory code we will have to be extra careful (we will need to wrap it in autoreleasing objects to make sure that resources are released).
We need to be careful with the border between our code and framework. If our exceptions leave our code, we could be in trouble (because frameworks may manually manage memory)
Did I miss anything? Are there additional cons/pros?
It looks like exceptions should be fine for library like code (when we have quite big amount of tightly packaged code, which doesn't communicate a lot with external systems/frameworks. And it looks like exception are hard to use for the code which actively interacts with other frameworks.
Does your experience prove this theory?
I appreciate any additional info on this subject.
tl;dr Exceptions should be used for fatal/non-recoverable/programmer error(s) only. Attempting to use them a la Java or other exceptions-are-recoverable environments will result in code that is more fragile, harder to maintain, and difficult to refactor while also limiting your ability to leverage system frameworks.
Con: If you use exceptions for flow control and/or recoverable errors in your code, your code will be, by design, different from Apple's design patterns.
End result?
• You can't use Apple's APIs at all in your code unless the border between your code and Apple's always isolates the exception behavior
• Every time your refactor, you'll have to refactor a mass of exception handling code
• Many things that should be trivial will be very complex; for example, you won't be able to put your objects into an enumerable collection and enumerate them without that enumeration -- block, for loop, whatever... -- also having exception processing at the boundaries.
Consider:
NSArray *a = #[yourExceptionfulInstance, yourExceptionfulInstance, yourExceptionfulInstance];
#try {
for(id k in a) { [k doSomething]; }
} #catch(...) {
}
If doSomething might raise, for any reason, the above is violation of the documented design patterns of the framework because you'll be throwing an exception across frames within Apple's framework(s).
That is one mighty big con. Big enough that I can't imagine a set of pros to outweigh it.

Simplify GCD blocks and methods [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I find myself often writing complex GCD / block based methods (comparable to the code snippet shown below).
How would you break up this kind of method in smaller
portions?
Would you rather GCD-enable the parsing methods in the managed
objects' code or would you rather keep the GCD code in the view
controller?
How can I run the NSURL request in the code below in the background
queue ([NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue] When I use NSOperationQueue
currentQueue, the completion handler does not get called.
Use a C function or a instance method to delegate certain processes (such as saving to the XML file).
Definitely keep it in the object's code. You are breaking MVC too much as it is,
Don't use NSURLRequest, use AFNetworking or RestKit instead.
I would separate that so you can actually see the MVC design in it. So I would have:
The UIViewController
A Manager Class to handle the interactions between the UIViewController, the NSURLConnection and the XML Parser
A class to handle the NSURLConnection (or any 3rd party you would like).
A class to handle the XML Parsing and posterior writing.
To establish communication I would use delegation. This way you would have different blocks of work. So when you need to change the XML Parse, just switch the class; if you need to use this logic somewhere else, just switch the UIViewController. Keep it simple and clean.
P.S: Sometimes, no matter what you do, the code just is, by it's nature, complex, please use comments, you will thank yourself later...

Why array pass by reference, but struct pass by value implicitly in C? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Why they design like this? I am very confused.
Update : I really want to know the answer of the question. I Googled but I can find nothing quite useful.
I think there maybe two reasons:
One : technical. Maybe it is hard to implement by the compiler (struct pass by reference). If the answer is this one. Please explain it.
Two: good for usage(programming). As i think, it is more elegant (or beautiful?), if struct pass by reference. I can not find some examples that show the advantage (strut pass by value). My programming career is not very long. In practice, I prefer to pass struct to a function as a pointer(pointer occupy less space on stack).
you may imagine array as a set containing consecutive memory location with the name of the array as the pointer to the first memory address of that set.
So it should be obvious now that when you pass an array by it's name, you are actually passing a copy of the address of that memory.
A structure, however is a set of objects, so when you pass a structure name, you are passing a copy of the objects in that set.
PS: this is a very basic C concept and an obvious doubt, better read a good C book to clear your concept further.
the array pass, actually is to pass address by value. In c, there has no pass by reference.
I think the reason to no pass whole value of array is that
first, the performance.
Second, since we can use the pointer as an array, the compiler can't know the size of memory that pointer points to, so can't to pass all value in array to function.
C definitely can be designed to know exact size of array, and pass value of array.But then, we can't use the pointer in array way, we can't use any malloc array.