Why is ConcurrentBag so slow in .Net (4.0)? Am I doing it wrong?

后端 未结 11 566
无人及你
无人及你 2020-12-08 04:05

Before I started a project, I wrote a simple test to compare the performance of ConcurrentBag from (System.Collections.Concurrent) relative to locking & lists. I am extr

11条回答
  •  温柔的废话
    2020-12-08 04:48

    You basically have very few concurrent writes and no contention (Parallel.For doesn't necessarily mean many threads). Try parallelizing the writes and you will observe different results:

    class Program
    {
        private static object list1_lock = new object();
        private const int collSize = 1000;
    
        static void Main()
        {
            ConcurrentBagTest();
            LockCollTest();
        }
    
        private static void ConcurrentBagTest()
        {
            var bag1 = new ConcurrentBag();
            var stopWatch = Stopwatch.StartNew();
            Task.WaitAll(Enumerable.Range(1, collSize).Select(x => Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5);
                bag1.Add(x);
            })).ToArray());
            stopWatch.Stop();
            Console.WriteLine("Elapsed Time = {0}", stopWatch.Elapsed.TotalSeconds);
        }
    
        private static void LockCollTest()
        {
            var lst1 = new List(collSize);
            var stopWatch = Stopwatch.StartNew();
            Task.WaitAll(Enumerable.Range(1, collSize).Select(x => Task.Factory.StartNew(() =>
            {
                lock (list1_lock)
                {
                    Thread.Sleep(5);
                    lst1.Add(x);
                }
            })).ToArray());
            stopWatch.Stop();
            Console.WriteLine("Elapsed = {0}", stopWatch.Elapsed.TotalSeconds);
        }
    }
    

提交回复
热议问题