生成随机布尔值的最快方法 [英] Fastest way to generate a random boolean

查看:761
本文介绍了生成随机布尔值的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,有几种方法可以在C#中创建随机布尔值:

So there is several ways of creating a random bool in C#:

  • 使用Random.Next():rand.Next(2) == 0
  • 使用Random.NextDouble():rand.NextDouble() > 0.5
  • Using Random.Next(): rand.Next(2) == 0
  • Using Random.NextDouble(): 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?

推荐答案

第一个选项-rand.Next(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);

,并在第二个选项-rand.NextDouble():

return this.Sample();

因为第一个选项包含maxValue验证,乘法和强制转换,所以第二个选项可能更快.

Since the first option contains maxValue validation, multiplication and casting, the second option is probably faster.

这篇关于生成随机布尔值的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆