I was recently given the task of determining if all of the 10,000 rows in a datagrid were expanded and also if all of the rows were collapsed. If either of these conditions exists, there were things that had to happen.
From the phrasing of the task, it seems that the All method would be a good fit. After I had written the code, it seemed to me I could use Any to speed it up.
When you have a boolean condition then All (condition) = not Any(not condition)
Try this test.
namespace AnyVersesAll
internal class Program
{
static List<bool> Booleans = new List<bool>();
static void Main(string[] args)
bool AreAllTrue = false;
PopulateBooleans();
sw.Start();
AreAllTrue = SearchWithAll();
sw.Stop();
Allms = sw.ElapsedMilliseconds;
sw.Restart();
AreAllTrue = SearchWithAny();
sw.Stop();
Anyms = sw.ElapsedMilliseconds;
Console.WriteLine(String.Format("All = {0}ms, Any = {1}ms", Allms, Anyms));
}
static void PopulateBooleans()
Booleans.Clear();
for (int i = 0; i < 10000; i++)
}
static bool SearchWithAll()
return Booleans.All(b => b); // are all true?
}
static bool SearchWithAny()
return !Booleans.Any(b => !b); // Are any false?
}
}
}
As you can see, Any is far faster than All because it stops as soon as it finds a match. I don't know why All doesn't stop as soon as it finds a non-match. Seems like an opportunity to me.
No comments:
Post a Comment