【问题标题】:Performance of generating pseudo-randomized values in .NET在 .NET 中生成伪随机值的性能
【发布时间】:2018-09-12 16:07:32
【问题描述】:

为什么

var random = new Random();
random.Next(0 /* or any other positive value */, int.MaxValue);

大约是以下速度的 1.5 倍:

random.Next(-1, int.MaxValue);

.NET Framework (4.7.2) 如何实现这些功能?他们不应该有差不多的表现吗?

(通过在循环中生成 10M 值来衡量性能)

编辑:-1 和 int.MaxValue 之间的范围是否可能太大,所以它必须在内部生成两个值?因为我在 -1 和 int.MaxValue-1 之间生成时看不到行为

【问题讨论】:

  • 你可以自己查看the source,第154行
  • 在@maccettura 评论的链接中,您可以看到if( range <= (long)Int32.MaxValue) 为您的第一个案例调用Sample(),为您的第二个案例调用GetSampleForLargeRange()。因此,确实,如果范围太大,则使用性能较差的方法。

标签: c# .net random .net-4.7.2


【解决方案1】:

根据 maccettura 的建议查阅源代码后,如果范围是 >Int32.MaxValue,则它使用性能较低的变体。

【讨论】:

    猜你喜欢
    • 2018-05-20
    • 2015-08-07
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    相关资源
    最近更新 更多