Friday, September 2, 2022

All vs Any

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.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
 
namespace AnyVersesAll
{
    internal class Program
    {
        static List<bool> Booleans = new List<bool>();
        static Random r = new Random();
 
        static void Main(string[] args)
        {
            bool AreAllTrue = false;
            Stopwatch sw = new Stopwatch();
            long Allms = 0;
            long Anyms = 0;
 
            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));
            Console.ReadLine();
        }
 
        static void PopulateBooleans()
        {
            Booleans.Clear();
            for (int i = 0; i < 10000; i++)
                Booleans.Add(r.Next(2) == 0);
        }
 
        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.