views:

106

answers:

3

I'm creating a Game of Life program for the iPhone and I want to be able to store previous states of the game in a large array, if I take the C approach and each "Grid" is a structure consisting of two ints for X, Y and a BOOL *array where I malloc the memory proportional to X*Y times the size of the BOOL value I can create 1000 of these 'Grids' at a resolution of 1024x768 in about .014 seconds but when I create an Objective-C type class that replicates this structure it takes .037 seconds. So since I want to speed this up as much as I can but still make the code bearable by adhering to Obj-C as much as possible I ask is there a way to allocate data quicker, I tried new but I can't seem to see why Obj-C doesn't support it!

Any ideas?

+5  A: 

'new' is C++, not objective C. You can rename your .m files to .mm to have it compiled in objective-C++ mode to support 'new', but if malloc() wasn't fast enough for you, then I doubt new is gonna help you any better.

5ound
uhm, Obj-C has new but for convenience only. it seems that nobody ever uses it:)
vodkhang
@vodkhang 5ound is referring to the `new` operator/keyword from C++, not to the `+new` method.
bbum
A: 

I think you should instead of calling malloc() 1000 times call it once and then set pointers into the memory block. That should be even faster. I don't think though that considering whether new or malloc is faster is the right approach, changing the algorithm usually 10 times more effective.

Anders K.
+2  A: 

Holy run-on question, batman, try using some punctuation and whitespace next time!

First, this new thing you speak of is a C++ism. You can't create an Objective-C instance via the new operator. Go read this wonderful doc to gain a deeper understanding of Objective-C.

Now, attempting to parse your question, it sounds like that:

  • you have tried creating 1,000 BOOL *s by calling malloc() 1,000 times?

  • ... and you have concluded that the relatively slowness of allocating 1,000 objects is a problem?

There is a more fundamental architectural problem here. Namely, that you trying to model down to such a fine-grained level with individual allocations, regardless of whether they are BOOL *s, Objective-C objects are anything else.

The minimum sized allocation that malloc() returns is generally 16 bytes. That one-bit BOOL (really, it is an 8 bit type; there are no single bit allocations) is gonna take up 16x more memory than it should.

You are for better off modeling your Grid as a single instance of the Grid class that contains all of the data. If you need a 10x10 grid with a flag at each point, just myBools = malloc(sizeof(BOOL) * 10 * 10). Then, any BOOL can be retrieve by myBools[col + (row * 10)] -- that is, it is trivial to map a 2D (or 3D) grid of gunk into a linear array.

bbum
+1 for the "holy run-on question, batman". `:-)`
kiamlaluno