NSMutableArray - Faster removal of many objects
Posted: Sun Sep 05, 2004 7:09 pm
An example entry.
This contains a full featured code snippet, that shows a faster way to remove objects than removeObjectsInArray when there is more than just a few objects to be removed. For readability there are no IMP optimizations.
The idea was useful at the end of 2002, is it still today ?
This contains a full featured code snippet, that shows a faster way to remove objects than removeObjectsInArray when there is more than just a few objects to be removed. For readability there are no IMP optimizations.
The idea was useful at the end of 2002, is it still today ?
Code: Select all
#import <Foundation/Foundation.h>
@interface NSMutableArray ( FastRemove)
- (void) removeManyObjectsInArray:(NSArray *) array;
@end
@implementation NSMutableArray ( FastRemove)
- (void) removeManyObjectsInArray:(NSArray *) array
{
NSHashTable *lut;
NSMutableArray *copy;
unsigned int m;
unsigned int n;
unsigned int i;
id p;
n = [array count];
m = [self count];
/* -- if u like --
if( n < 16 || m < 16 || n * m < 1024) // guessed values where
copying does not pay off
{
[self removeObjectsInArray:array];
return;
}
*/
lut = NSCreateHashTable( NSNonRetainedObjectHashCallBacks, n);
for( i = 0; i < n; i++)
NSHashInsertIfAbsent( lut, [array objectAtIndex:i]);
copy = [NSMutableArray arrayWithCapacity:m];
for( i = 0; i < m; i++)
{
p = [self objectAtIndex:i];
if( ! NSHashGet( lut, p))
[copy addObject:p];
}
NSFreeHashTable( lut);
[self setArray:copy];
}
@end