It is currently Thu Dec 14, 2017 7:45 pm

Mulle kybernetiK Optimization

Forum for Optimizations around Cocoa and Mac OS X

NSMutableArray - Faster removal of many objects

Optimizations concerning <i>Foundation</i> or <i>Objective-C</i> and its runtime
User avatar
 
Posts: 42
Joined: Fri Aug 06, 2004 9:20 am
Location: Bochum
Website: http://www.mulle-kybernetik.com/weblog

NSMutableArray - Faster removal of many objects

Post by Nat! » 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 ?

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

User avatar
 
Posts: 42
Joined: Fri Aug 06, 2004 9:20 am
Location: Bochum
Website: http://www.mulle-kybernetik.com/weblog

Re: NSMutableArray - Faster removal of many objects

Post by Nat! » Thu Feb 03, 2005 3:33 pm

Nat! wrote:An example entry.
The idea was useful at the end of 2002, is it still today ?

Sure is, had to use it again in 2005.


Return to “Foundation & Objective-C”

Who is online

Users browsing this forum: No registered users and 1 guest