1
private static Int64 NextInt64(Random rnd) 
{     
    var buffer = new byte[sizeof(Int64)];     
    rnd.NextBytes(buffer);     
    return BitConverter.ToInt64(buffer, 0); 
} 

above method is from this thread: Generate random values in C#

It will be used in an abstract event class to generate unique eventId. that class will be used frequently because we need to send lots of event. When I call above method in the event class constructor which option is better from the performance and unique value point of view:

  1. create a Random object with new and pass it into above method each time;
  2. create a static Random object at very beginning and use it to call above method repeatedly when needed.
Community
  • 1
  • 1
5YrsLaterDBA
  • 33,370
  • 43
  • 136
  • 210
  • 3
    Why not use Guids and then `Guid.NewGuid()`? (a comment because it desn't answer your question - it's more about the validity of this code for random values) – Andras Zoltan Apr 15 '11 at 15:46
  • 2
    it's a valid comment - using random to generate **unique** numbers is a poor decision. – MattDavey Apr 15 '11 at 15:51
  • 1
    I can't stress enough the folly of using a random number as a "unique key". With a 64-bit random number, there is a 1% chance of generating a duplicate after about 610 million items. It's *possible* to generate the same number twice in a row. I strongly suggest that you use some other method of generating a unique key. – Jim Mischel Apr 15 '11 at 16:32

4 Answers4

3

You're definitely better off creating one Random instance and using it multiple times. You will achieve better 'randomness' that way.

If you check out microsoft's documentation here you'll see that two Random instances produce the exact same numbers.

Another way to get 'better' random numbers is to provide a seed. Some pass the current time as an int to get a very unique seed.

Liz
  • 8,780
  • 2
  • 36
  • 40
  • 3
    The parameterless constructor passes the current time (from `Environment.TickCount`) as the seed. The most common reason to use the other constructor is if you want to make sure that the same sequence of random numbers is generated each time, often for testing purposes. – Jim Mischel Apr 15 '11 at 16:13
  • A good real world example is in networked video games - where the simulation is being carried out on several client machines, you may want to make sure that each client machine is generating the same random numbers in the same order.. – MattDavey Apr 18 '11 at 07:56
2
  • You need option 2) anyway, otherwise al your random's will be the same. See this.
  • you can turn this method into an extenison,

Like this:

 public static class Helpers
 {
   public static Int64 NextInt64(this Random rnd) { ... }
 }

But ...

It will be used in an abstract event class to generate unique eventId.

No, this will not generate unique Id's . Be prepared for collisions.

Use a simple counter (nextId) or GUids

Community
  • 1
  • 1
H H
  • 263,252
  • 30
  • 330
  • 514
2

System Guid structure is exactly for this purpose. Rather than trying to pass on a seemingly randomized object, pass a guid structure as an argument.

private static Guid  NextIntGuid() 
{
  return Guid.NewGuid();
}

As the name implies, it is already for representing a globally unique identifiers. Also if you insist on using random numbers, use RandomNumberGenerator inside the System.Security.Cryptography namespace. If sufficiently large, your random number will almost unique:

byte[] random = new Byte[128];

//RNGCryptoServiceProvider is an implementation of a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(random); // The array is now filled with cryptographically strong random bytes.
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • Quit a hefty function for Id generation, and back to Randomness to prevent collisions. – H H Apr 15 '11 at 18:58
1

1 will cause issues with randomness unless you give it a unique seed each time. Not to mention putting extra pressure on the garbage collector.

2 is a better option - the Random class is designed to generate a sequence of random numbers, not just one. So while it's better to have a single instance of Random, it doesn't necessarily need to be accessible with a static property, it could be exposed in any number of ways.

MattDavey
  • 8,897
  • 3
  • 31
  • 54