General Performance: Optimizing Random Number Generation

This is an excerpt from: Rock Your Code: Code and App Performance for Microsoft .NET

The Random type in .NET has been a go-to for generating random numbers since the platform’s inception. Below is an example illustrating its usage in creating a byte array.

private static readonly Random _random = new();

private byte[] GenerateByteArray(double sizeInKb)
{
    var bytes = new byte[Convert.ToInt32(sizeInKb * 1024)];

    lock (_lock)
    {
        _random.NextBytes(bytes);
    }

    return bytes;
}

A more performance-efficient approach to generating random numbers involves utilizing the, as demonstrated below.

private static readonly RandomNumberGenerator _randomNumberGenerator = RandomNumberGenerator.Create();

private byte[] GenerateByteArray(double sizeInKb)
{
    var bytes = new byte[Convert.ToInt32(sizeInKb * 1024)];

    lock (_lock)
    {
        _randomNumberGenerator.GetBytes(bytes);
    }

    return bytes;
}

Performance Breakdown

The benchmark results show that using RandomNumberGenerator provides a 7.08× speed improvement compared to the alternative method. Both approaches allocate the same amount of memory.

When generating random numbers, prefer RandomNumberGenerator for its superior performance and security, especially in scenarios where cryptographic strength or scalability are important.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.