iPhone Objective-C、malloc 还是 NSMutableData?
我需要使用易失性内存块来使用多个线程不断写入和重写内部数据。如果我使用 malloc 数据或 NSMutableData,则数据将使用 @synchronized 呈现为线程安全的。
我的问题是,对于速度而言,更推荐什么?看到我正在数据矩阵上运行递归计算方程,我需要能够尽快分配、检索和设置数据。
我打算对这个主题进行自己的研究,但我想知道是否有人知道 Objective-C NSMutableData 的开销是否会导致速度下降?
I'm need to use a volitile block of memory to constantly write and rewrite the data inside using multiple threads. The data will be rendered thread-safe using @synchronized if I utilize either malloc'd data or NSMutableData.
My question is what is more recommended for speed? Seeing I'm running recursivly calculated equations on the matrix of data I need to be able to allocate, retrieve, and set the data as quickly as possible.
I'm going to be doing my own research on the subject but I was wondering if anyone knew off-hand if the overhead of the Objective-C NSMutableData would introduce speed setbacks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
回复:psychotik 的建议:
volatile
是 C 中的一个关键字,它基本上告诉编译器避免优化其所附加符号的使用。这对于多线程代码或直接与硬件交互的代码很重要。然而,它对于处理内存块(来自malloc()
或NSData
)来说并不是很有用。正如psychotik所说,它用于诸如之类的原语。 int
或指针(即指针本身,而不是它指向的数据。)它不会使您的数据访问速度更快,实际上可能会因为破坏编译器的优化技巧而减慢数据访问速度。对于跨线程同步,我认为,如果您不需要递归访问,最快的选择是
OSSpinLock
,或者如果需要,则将pthread_mutex
设置为递归。请记住,顾名思义,OSSpinLock
是一个自旋锁,因此某些使用模式使其效率低于pthread_mutex
,但它也非常接近金属(它基于硬件的原子获取/设置操作。)如果您的数据确实被频繁访问,以至于您担心锁定性能,您可能希望避免使用 NSData 并只使用来自
malloc()
的内存块 - 但是,如果不了解您要完成的任务或访问数据的频率,解决方案不会轻易出现。您能告诉我们更多关于您的意图吗?re: psychotik's suggestion:
volatile
is a keyword in C that basically tells the compiler to avoid optimizing usage of the symbol it's attached to. This is important for multithreaded code, or code that directly interfaces with hardware. However, it's not very useful for working with blocks of memory (frommalloc()
orNSData
.) As psychotik said, it's for use with primitives such as anint
or a pointer (i.e. the pointer itself, not the data it points to.) It's not going to make your data access any faster, and may in fact slow it down by defeating the compiler's optimization tricks.For cross-thread synchronization, your fastest bet is, I think, an
OSSpinLock
if you don't need recursive access, or apthread_mutex
set up as recursive if you do. Keep in mindOSSpinLock
is, as the name suggests, a spin lock, so certain usage patterns make it less efficient than apthread_mutex
, but it's also extremely close to the metal (it's based off the hardware's atomic get/set operations.)If your data really is being accessed frequently enough that you're concerned with locking performance, you'll probably want to avoid
NSData
and just work with a block of memory frommalloc()
--but, without knowing more about what you're trying to accomplish or how frequently you're accessing the data, a solution does not readily present itself. Can you tell us more about your intent?