I have two NSArray objects and I want to add the two arrays together in a component wise fashion such that the int in array1 at index i is added to the int in array 2 at index i with the result added to a new array. Is there a faster way to do this than with standard for for (int i=0; i<[array1 count]; i++) type methods? For example, can you use c arrays, fast enumeration, blocks? I am particularly interested because I would like to add x number of arrays containing large number of objects. My current code is as follows:
NSArray *array1 = [NSArray arrayWithObjects:
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
[NSNumber numberWithInt:4],
nil];
NSArray *array2 = [NSArray arrayWithObjects:
[NSNumber numberWithInt:10],
[NSNumber numberWithInt:20],
[NSNumber numberWithInt:30],
[NSNumber numberWithInt:40],
nil];
NSMutableArray *resultArray = [[NSMutableArray alloc] initWithCapacity:[array1 count]];
for (int i=0; i<[array1 count]; i++) {
int result = [[array1 objectAtIndex:i] intValue] + [[array2 objectAtIndex:i] intValue];
[resultArray addObject:[NSNumber numberWithInt:result]];
}
Thanks, I appreciate any comments.
Here an example of doing this with blocks and concurrent enumeration:
Whether it’s faster or not would require profiling to determine. My hunch is that it’s not much faster, and may even be slower because of the (relatively small, but still extant) overhead of GCD dispatches. However, for more complex computation than simple addition, this gives you an idea of how to use concurrent enumeration to easily do something with each element in an array in a multicore-aware way.
If you had x number of arrays in a top-level array (as described in your comment), you could replace the -enumerateObjectsWithOptions:usingBlock: call with something like this:
dispatch_apply()is a Grand Central Dispatch function that simply runs a block of code a specified number of times. Since we’re telling it to use a global concurrent queue that we got withdispatch_get_global_queue(), it can run different invocations of the block concurrently, providing a (possible) performance benefit on multicore machines. As with most programming problems, there are plenty of other ways to approach this problem. This is just one that came to mind for me.