What is the cost of using exceptions in Objective-C?
I mean in the current implementation of clang or the gcc version.
C++ and Java guys always tell me that exceptions do not cost any performance unless they are thrown. Is the same true f开发者_如何学Goor Objective-C?
C++ and Java guys always tell me that exceptions do not cost any performance unless they are thrown. Is the same true for Objective-C?
Short Answer
Only in 64-bit OS X and iOS.
They're not entirely free. To be more precise, the model is optimized to minimize costs during regular execution (moving consequences elsewhere).
Detailed Answer
On 32 bit OS X and iOS, exceptions have runtime costs even if they are not thrown. These architectures do not use Zero Cost Exceptions.
In 64 bit OS X, ObjC moved over to borrow C++'s "Zero Cost Exceptions". Zero Cost Exceptions have very very low execution overhead, unless thrown. Zero Cost Exceptions effectively move execution cost to binary size. This was one of the primary reasons they were not initially used in iOS. Enabling C++ exceptions and RTTI can increase the binary size by more than 50% -- of course, I would expect those numbers to be far lower in pure ObjC simply because there is less to execute when unwinding.
In arm64, the exception model was changed from Set Jump Long Jump to Itanium-derived Zero Cost Exceptions (judging by the assembly).
However, Idiomatic ObjC programs are not written or prepared to recover from exceptions, so you should reserve their use for situations which you do not intend to recover from (if you decide to use them at all). More details in the Clang manual on ARC, and in other sectons of the referenced page.
According to some 2007 release notes for the Objective-C runtime in Mac OS X v10.5, they have re-written the 64bit implementation of Objective-C exceptions to provide "zero-cost" try blocks and interoperability with C++.
Apparently, these "zero-cost" try blocks incur no time penalty when entering a try, unlike its 32-bit counterpart which must call setjmp() and other functions. Apparently throwing them is "much more expensive".
This is the only bit of information I can find in Apple's release notes so I would have to assume that this still applies in todays runtimes, and as such, 32bit exceptions = expensive, 64-bit exceptions = "zero-cost"
精彩评论