Kristen Martinson
Kristen Martinson

Reputation: 1869

speeding up NSMutableArray declaration?

I need to speed up declaration of a 2d array and the following "example" is too slow where allocation is done as it comes. How can I do the allocation 10 columns where each column may have up to 20 elements... letting the remainders be nil/null. Is there automation for this or do I have to loop through each column and addObjects(SLOW) and init with 20 objects of nil?

ppp = [NSMutableArray arrayWithCapacity: 10];

[ppp addObject:[[NSMutableArray alloc] initWithObjects:
                    @"1",
                    @"2",
                    @"3",
                    @"4",
                    nil
                    ]];

[ppp addObject:[[NSMutableArray alloc] initWithObjects:
                    @"a1",
                    @"b2",
                    @"c3",
                    nil
                    ]];

thanks...

(let me put it this way: in "standard-c" I can declare "*char person[100][100]"... declaration of space is done. Now just write to the addresses. Dynamical allocation is a lot of row swapping that is cpu and memory consuming. Is there anything in "Objective-c" to accomplish something that does NSArray *person[100][100] ?? )

Upvotes: 1

Views: 215

Answers (1)

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

Instead of using an array of arrays, as you do, why don't you use a single NSMutableArray and calculate the rows and columns? I know that your 2d array is ragged, i.e. each "sub"array may have a different length, but you could calculate the max. "width" and max "height" of your table and simply leave some items free:

ppp = [[NSMutableArray alloc] initWithObjects:
    @"1", @"2", @"3", @"4", @"", @"",
    @"a1", @"b2", @"c3", @"", @"", @"",
    etc...
    ];

Now you simply calculate item[1,2] as itemAt: 6*1 + 2.

Not sure if that helps, but it might speed up things.

An alternative is to use simple C arrays instead.

Upvotes: 1

Related Questions