So there is several ways of creating a random bool in C#:
rand.Next(2) == 0
rand.NextDouble() > 0.5
Is there really a difference? If so, which one actually has the better performance? Or is there another way I did not see, that might be even faster?
The first option - rand.Next(2)
executes behind the scenes the following code:
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException("maxValue",
Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", new object[] { "maxValue" }));
}
return (int) (this.Sample() * maxValue);
and for the second option - rand.NextDouble()
:
return this.Sample();
Since the first option contains maxValue
validation, multiplication and casting, the second option is probably faster.