简体   繁体   English

在Objective-C中使用C风格的数组

[英]Using C-style arrays in Objective-C

Let's say that I want to use C-style arrays of NSObjects instead of using NSArray. 假设我想使用NSObject的C风格数组而不是使用NSArray。 Does this have any performance penalties over the usage of NSArray? 这对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. 你交易的是相当多的NSArray功能和合理的封装量,如果你不小心,会给你一些语法上的麻烦和内存泄漏的风险。

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. 我把这个逻辑隐藏在一个带有二维索引的NSArray的自定义模拟中。 An early implementation used a dictionary with NSIndexPath s as keys. 早期的实现使用带有NSIndexPath的字典作为键。 That was quite slow. 那很慢。 I tried an NSArray of NSArray s. 我尝试了NSArrayNSArray That was slower. 那个慢了。 I tried a 2d C array and that was significantly faster. 我尝试了一个2d C阵列,这明显更快。 Having taken the time to balance my retain s and release s there were no ill consequences for performance. 花时间平衡我的retainrelease对性能没有任何不良后果。

Although there is no performance penalty for it, there is certainly a loss of flexibility: unlike NSMutableArray s, your C arrays are fixed-size. 虽然它没有性能损失,但肯定会失去灵活性:与NSMutableArray不同,你的C数组是固定大小的。 You would not be able to use fast enumeration with C arrays, too, having to resort to using array indexes. 您也无法使用C数组的快速枚举,不得不求助于使用数组索引。

If these limitations are OK with your requirements, C arrays should work. 如果这些限制符合您的要求,C阵列应该可以工作。 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 . 它们也很适合ARC:一旦C数组的强引用超出范围,ARC就会释放所有未设置为nil实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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