D idom for removing array elements

Dukc via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 27 00:15:56 PST 2017


On Friday, 27 January 2017 at 05:48:27 UTC, Stefan Koch wrote:
> To me it looks rather slow.
> please benchmark!

void main()
{   import std.stdio, std.algorithm, std.range, std.array, 
std.datetime;
     int[] a = [1, 2, 3, 4, 5, 6, 7, 4].cycle.take(2000).array;
     int[] b = [3, 4, 6].cycle.take(2000).array;

     void originalMethod()
     {   auto c = a.remove!(x => b.canFind(x));
         assert(c[0 .. 4] == [1, 2, 5, 7]);
     }

     void WilsonMethod()
     {   auto c = a.filter!(x => !b.canFind(x)).array;
         assert(c[0 .. 4] == [1, 2, 5, 7]);
     }

     void myMethod()
     {   auto sortedB = sort(b.dup);
         auto c = a
         .   filter!(i => !sortedB.contains(i))
         .   array
         ;
         assert(c[0 .. 4] == [1, 2, 5, 7]);
     }

     auto r = benchmark!(originalMethod, WilsonMethod, 
myMethod)(1);
     foreach(result; r) result.writeln;
}

resulted in:
TickDuration(28085)
TickDuration(42868)
TickDuration(1509)

So, you were correct that the original method is better than 
Wilsons filter. My method is much better for large arrays I 
tested here. But what I think you were afraid of is that it 
needlessly wastes performance by allocating a new array, and I 
agree.

Also, as I said, it could be made O(n).


More information about the Digitalmars-d-learn mailing list