简体   繁体   中英

Using C-style arrays in Objective-C

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?

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 NSIndexPath s as keys. That was quite slow. I tried an NSArray of NSArray s. That was slower. I tried a 2d C array and that was significantly faster. Having taken the time to balance my retain s and release s there were no ill consequences for performance.

Although there is no performance penalty for it, there is certainly a loss of flexibility: unlike NSMutableArray s, 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM