I have a mutable array with contents I want to replace with NSNull objects. This is what I do:
NSMutableArray* nulls = [NSMutableArray array];
for (NSInteger i = 0; i < myIndexes.count; i++)
[nulls addObject:[NSNull null]];
[stageMap replaceObjectsAtIndexes:myIndexes withObjects:nulls];
How can I do this more efficiently? Is there a way to enumerate an NSIndexSet, so I can replace the array content one by one?
Solved
Suggested method turns out to be 2x faster (avg 0.000565s vs 0.001210s):
if (myIndex.count > 0)
{
NSInteger index = [myIndex firstIndex];
for (NSInteger i = 0; i < myIndex.count; i++)
{
[stageMap replaceObjectAtIndex:index withObject:[NSNull null]];
index = [myIndex indexGreaterThanIndex:index];
}
}
-
You can use a
for
loop. Start with the first index, useindexGreaterThanIndex:
to get the next index, and stop after you hit the last index.Don't forget to account for an empty index set. Both the first and last index will be
NSNotFound
in that case. The easiest way is to test the index set's count; if it's zero, don't loop.Also, what Jason Coco said about profiling. Don't worry too much about efficiency until your program works, and don't go optimizing things until you have run Shark (or Instruments, if that's your thing) and found exactly what is slow.
hyn : Thanks for the tip. I will try to benchmark this and see if the new approach is any faster.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.