0

Why is

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

about 1.5 times as fast as:

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

How does the .NET Framework (4.7.2) implement this functions? Shouldn't they have about the same performance?

(performance measured by generating 10M values in a loop)

Edit: Is it possible that the range between -1 and int.MaxValue is too big so it has to generate two values internally? Because I don't see the behavior when generating between -1 and int.MaxValue-1

D.R.
  • 20,268
  • 21
  • 102
  • 205
  • 3
    You can check [the source](https://referencesource.microsoft.com/#mscorlib/system/random.cs) yourself, line 154 – maccettura Sep 12 '18 at 16:11
  • 1
    In the link from @maccettura's comment you can see that `if( range <= (long)Int32.MaxValue)` calls `Sample()` for your first case and `GetSampleForLargeRange()` for your second case. So indeed, if the range is too big, a less performing method is used. – Olivier Jacot-Descombes Sep 12 '18 at 17:02

1 Answers1

0

After consulting the source code as recommended by maccettura, if the range is >Int32.MaxValue it uses a less performant variant.

D.R.
  • 20,268
  • 21
  • 102
  • 205