Jacob
Jacob

Reputation: 23

Allocating objective-c objects in a contiguous chunk of memory

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.

Upvotes: 1

Views: 1187

Answers (3)

bbum
bbum

Reputation: 162712

This sounds more like you should be using C / C++ for the game engine with a veneer of Objective-C over the top to make it easy to use.

That is, assuming that you've measured a performance issues that can really only be fixed by contiguous layout of objects in memory.

Upvotes: 1

Jim
Jim

Reputation: 73936

If you're worrying about performance to the point where you are analysing cache misses, then you are probably better writing your code in C with only a minimal Objective C layer. But is this necessary? Have you profiled your code and determined that cache misses are slowing your code down?

If you're serious about having to manually allocate memory, you'll want to check out Memory Allocation Techniques.

Upvotes: 1

Ole Begemann
Ole Begemann

Reputation: 135548

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:

An Objective-C object is just a chunk of memory with the right size, and with the first pointer-sized chunk set to point at the object's class. A custom allocator thus needs to return a pointer to a properly-sized chunk of memory, with the class filled out appropriately.

So you could allocate a large amount of memory (with calloc()) first and then your allocWithZone: method could reserve a space in this large chunk of memory at the correct position.

Upvotes: 5

Related Questions