实例化循环内或循环外 [英] Instantiating Random in or out of the loop

查看:68
本文介绍了实例化循环内或循环外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常以以下方式生成随机内容:

I usually generate random stuff in the following manner:

Random random = new Random(DateTime.Now.Millisecond);

for (int i = 0; i < 100; i++)
{
    Console.WriteLine(random.Next(0, 100));
}

我想知道是否将Random实例放在循环中是否有区别:

I was wondering whether there is a difference if I put the Random instantiation within the loop:

for (int i = 0; i < 100; i++)
{
    Random random = new Random(DateTime.Now.Millisecond);

    Console.WriteLine(random.Next(0, 100));
}

哪个是随机的还是相同的?

Which is more random or they are the same?

推荐答案

第一个(即循环外)效率更高,更随机,因为第二个在很短的时间内创建了许多 Random 实例这将导致多个实例具有相同的种子(即,相同的 Millisecond ),这又意味着一次又一次地生成相同的随机数.

The first (i.e. outside the loop) is more efficient AND more random since the second creates lots of Random instances in very short time which will lead to several instances having the same seed (i.e. same Millisecond) which in turn means generating the same random numbers over and over again.

来自 MSDN

随机数生成从种子值开始.如果一样重复使用种子,会生成相同的数字序列.

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated.

这篇关于实例化循环内或循环外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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