Fastest way to generate a random boolean
Small enhancement for the second option:
According to MSDN
public virtual double NextDouble()
returns
A double-precision floating point number greater than or equal to 0.0, and less than 1.0.
So if you want an evenly spread random bool you should use >= 0.5
rand.NextDouble() >= 0.5
Range 1: [0.0 ... 0.5[
Range 2: [0.5 ... 1.0[
|Range 1| = |Range 2|
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.