Pointers or copies?

Chris Nicholson-Sauls ibisbasenji at gmail.com
Thu Dec 21 06:44:31 PST 2006


Hasan Aljudy wrote:
> * You can remove an element from the array using a slicing trick:
> void remove( Object[] array, int i )
> {
>      array = array[0..i] ~ array[i+1..$];
> }
> I haven't tested this but it should work, although I suspect it maybe 
> suboptimal.
> The $ inside the slice refers to array.length.

It is "suboptimal" but not by /too/ much.  Cashew uses C's memmove thanks to a couple of 
other D'ers who proved the performance differences.  (I only mention it because he 
specifically said he's writing games, and performance would therefore be important.)  In 
case he doesn't want all of Cashew, the implementation of .drop follows:

void drop (T) (inout T[] haystack, size_t index)
in {
   assert(index < haystack.length, ".drop() called with index greater than array length");
}
body {
   if (index != haystack.length - 1) {
     memmove(&(haystack[index]), &(haystack[index + 1]), T.sizeof * (haystack.length - 
index));
   }
   haystack.length = haystack.length - 1;
}


-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list