开发者

which way is better to call this id generation method?

开发者 https://www.devze.com 2023-02-26 02:48 出处:网络
private static Int64 NextInt64(Random rnd) { var buffer = new byte[s开发者_如何学运维izeof(Int64)];
private static Int64 NextInt64(Random rnd) 
{     
    var buffer = new byte[s开发者_如何学运维izeof(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.


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.


  • 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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消