brianSan
brianSan

Reputation: 535

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?

Upvotes: 3

Views: 1175

Answers (2)

Tommy
Tommy

Reputation: 100652

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.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727017

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.

Upvotes: 2

Related Questions