I want to allocate x number of objects from a certain objective-c class in such a way that they are laid out contiguously in memory. The platform is iOS.
The actual problem I want to solve is how to store those x objects in memory such that I can iterate over them with as few cache misses as possible. I was thinking of creating a simple c-style array of objective-c objects, but when I allocate such an object with Obj *obj = [[object alloc] init]; and assign this to an index in my array, I am just storing the pointer, so this obviously does not work.
How can I accomplish this?
EDIT: Some more background: I am trying to apply data-oriented design to my iOS game engine, and I believe that laying out objects in memory this way would give me an easy performance gain (am I wrong?) as my current engine would require minimal adjustments.
If you really want to do this (don’t optimize unless you’re certain you are facing a bottleneck), you would have to override the
+allocWithZone:method for your class. I suggest you read Mike Ash’s wonderful recent article Custom Object Allocators in Objective-C. Quoting from it:So you could allocate a large amount of memory (with
calloc()) first and then yourallocWithZone:method could reserve a space in this large chunk of memory at the correct position.