DEV Community

Volkan Alkılıç
Volkan Alkılıç

Posted on • Updated on

A small benchmark to compare concurrent data structures in C#

The advantage of using concurrent data structures is that they allow you to write highly concurrent code that can take advantage of multiple CPU cores and run faster on multi-core systems. By using these data structures, you can avoid the overhead and complexity of manually implementing synchronization in your code, which can be error-prone and lead to race conditions and other concurrency issues.

    static void Main(string[] args)
    {
        // Set the number of iterations and threads to use in the benchmark
        const int numIterations = 1000000;
        const int numThreads = 8;

        // Create a stopwatch to measure the time it takes to complete the benchmarks
        Stopwatch stopwatch = new Stopwatch();

        // Benchmark the concurrent queue
        stopwatch.Start();
        ConcurrentQueue<int> queue = new ConcurrentQueue<int>();
        Parallel.For(0, numThreads, i =>
        {
            for (int j = 0; j < numIterations; j++)
            {
                queue.Enqueue(j);
                queue.TryDequeue(out _);
            }
        });
        stopwatch.Stop();
        Console.WriteLine($"ConcurrentQueue: {stopwatch.ElapsedMilliseconds} ms");

        // Benchmark the concurrent stack
        stopwatch.Reset();
        stopwatch.Start();
        ConcurrentStack<int> stack = new ConcurrentStack<int>();
        Parallel.For(0, numThreads, i =>
        {
            for (int j = 0; j < numIterations; j++)
            {
                stack.Push(j);
                stack.TryPop(out _);
            }
        });
        stopwatch.Stop();
        Console.WriteLine($"ConcurrentStack: {stopwatch.ElapsedMilliseconds} ms");

        // Benchmark the concurrent dictionary
        stopwatch.Reset();
        stopwatch.Start();
        ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();
        Parallel.For(0, numThreads, i =>
        {
            for (int j = 0; j < numIterations; j++)
            {
                dictionary.TryAdd(j, j);
                dictionary.TryRemove(j, out _);
            }
        });
        stopwatch.Stop();
        Console.WriteLine($"ConcurrentDictionary: {stopwatch.ElapsedMilliseconds} ms");

        Console.ReadKey();
    }

Enter fullscreen mode Exit fullscreen mode

Join Me

Follow me on Twitter and Linkedin for more content.

Top comments (0)