Using the code below I got the following results:
100000000 00:00:45.9990976
200000000 00:00:21.1352109
300000000 00:00:17.3039397
So,
for the given data...
Set.IsSupersetOf
is quickest and I recommend it for your needs (whatever they are).
Set.IsSubsetOf
is not quite as quick -- I expect it has to iterate more of the List.
And the Linqish
List.Except
is worst, including the situation that if you just want a boolean then there is no need to produce a collection and then count the items in the collection.
Consider, that when seeking a boolean, the process can be short-circuited as soon as one item is found outside the target. I certainly hope that
IsSupersetOf
and
IsSubsetOf
do that.
Except
certainly does
not short-circuit and then it makes you perform another operation (like
Count
) before you can get your result.
using System.Linq ;
using StringList=System.Collections.Generic.List<string> ;
using StringSet=System.Collections.Generic.HashSet<string> ;
int reps = 100000000 ;
StringList list1 = new StringList { "a" , "b" , "c" , "z" } ;
StringList list2 = new StringList { "a" , "b" , "c" , "d" } ;
StringSet set1 = new StringSet ( list1 ) ;
StringSet set2 = new StringSet ( list2 ) ;
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch() ;
sw.Restart() ;
for ( int i = 0 ; i < reps ; i++ )
result += list2.Except(list1).Count()==0 ? 0 : 1 ;
sw.Stop() ;
System.Console.WriteLine ( "{0} {1}" , result , sw.Elapsed ) ;
sw.Restart() ;
for ( int i = 0 ; i < reps ; i++ )
result += set2.IsSubsetOf ( list1 ) ? 0 : 1 ;
sw.Stop() ;
System.Console.WriteLine ( "{0} {1}" , result , sw.Elapsed ) ;
sw.Restart() ;
for ( int i = 0 ; i < reps ; i++ )
result += set1.IsSupersetOf ( list2 ) ? 0 : 1 ;
sw.Stop() ;
System.Console.WriteLine ( "{0} {1}" , result , sw.Elapsed ) ;