Linq’s count () was too slow.

1 minute read

LINQ count is slow

I was doing paiza because I had too much free time, but there was a test case that timed out.
After fixing the part written in Linq, the test passed, so I investigated the speed.
Use a simple self-made function and LINQ count to count the number of elements above a certain number and measure the processing speed.

code

        static void Main(string[] args)
        {
            List<int> inputs = new List<int>();
            var sw = new System.Diagnostics.Stopwatch();
            int target = 1000;
            int inputCount = 100000;

            //Element injection
            for (int i = 0; i < inputCount; i++)
            {
                inputs.Add(i);
            }

            //self made
            sw.Start();
            int cnt1 = BigCount(inputs, target, inputCount);
            sw.Stop();
            TimeSpan time = sw.Elapsed;
            Console.WriteLine("result(self made) /Element count:"+cnt1 +" /processing speed:"+ time);

            //Linq
            sw.Restart();
            int cnt2 = inputs.Count(m => m >= target);
            sw.Stop();
            TimeSpan time2 = sw.Elapsed;
            Console.WriteLine("result(Linq) /Element count:" + cnt2 + " /processing speed:" + time2);
        }

        //Returns the number of elements greater than or equal to target
        public static int BigCount(List<int> inputs, int target, int inputCount)
        {
            int ret = 0;
            for (int i = 0; i < inputCount; i++)
            {
                if (inputs[i] >= target)
                {
                    ret++;
                }
            }
            return ret;
        }

result

result(self made) /Element count:99000 /processing speed:00:00:00.0004307
result(Linq) /Element count:99000 /processing speed:00:00:00.0011384

There was a difference of about 3 times.
Since it is almost an error, you should use Linq, which is easy to read in practice!

Tags:

Updated: