Understanding Objective-C's dynamic runtime
-
14-09-2019 - |
Question
I'm getting my feet wet in Objective-C and Cocoa (I know, probably late, but hey I have to start somewhere) and I noticed that all objects are allocated out of the heap.
Is there any reason why this is the standard in Objective-C? I tried looked everywhere (and yes, even on StackOverflow), but I couldn't find any explicit reason, except "that is how it is". I'm especially keen because Objective-C is considered a strict super-set of C with OO features.
If I missed an article on the InterBlag or a post on StackOverflow by mistake on this topic, please initiate graceful shutdown. :)
Solution
I think this owes to the Smalltalk heritage.
Also, you could say that stack-allocated objects are a peculiarity of C++. Very few other languages do that, and then mostly as a low-level optimization for the compiler. In C++ it's reasonable, since one of the stated goals was to be exactly as performant as plain C.
Why do you feel this is in conflict with the fact that Objective-C is a super-set of C? After all, plain C can't either allocate objects on the stack... nor anywhere. struct
s, OTOH, are allowed on the stack, both on C and Objective-C
OTHER TIPS
I'm not exactly answering your question, but since you are understanding Obj-C's runtime, here it goes. You can allocate objects more efficiently using NSZones. You won't have them on the stack, but at least you can avoid some fragmentation and performance issues: link text