Let's say that I want to use C-style arrays of NSObjects instead of using NSArray. Does this have any performance penalties over the usage of NSArray?
-
I don't believe so. For most of these kind of things there are toll-free bridges.onnoweb– onnoweb2012-06-29 18:11:23 +00:00Commented Jun 29, 2012 at 18:11
-
4@onnoweb: "toll-free bridges" are used between Core Foundation objects and Foundation objects, the concept does not apply to anything else.Dietrich Epp– Dietrich Epp2012-06-29 18:14:28 +00:00Commented Jun 29, 2012 at 18:14
2 Answers
There are no performance penalties, indeed technically there should be a performance improvement. What you trade away is quite a lot of the NSArray functionality and a reasonable amount of encapsulation, giving you some syntax headaches and a risk of memory leakage if you're not careful.
That said, one app I worked on involved a 2d array of data. Conveniently the array was a fixed size, known in advance. I hid the logic for that inside a custom analogue of NSArray that took two-dimensional indices. An early implementation used a dictionary with NSIndexPaths as keys. That was quite slow. I tried an NSArray of NSArrays. That was slower. I tried a 2d C array and that was significantly faster. Having taken the time to balance my retains and releases there were no ill consequences for performance.
1 Comment
Although there is no performance penalty for it, there is certainly a loss of flexibility: unlike NSMutableArrays, your C arrays are fixed-size. You would not be able to use fast enumeration with C arrays, too, having to resort to using array indexes.
If these limitations are OK with your requirements, C arrays should work. They play nicely with ARC, too: once a C array of strong references goes out of scope, ARC releases all instances that are not set to nil.
2 Comments
NSEnumerator pattern only.for : in construct would not be available. I agree, the speed of indexing would be much faster, because there would be no copying that's hidden inside implementations of fast enumeration.