Providing objects with unique IDs onStart
3 answers
This method does not provide a unique identifier for multiple instances of your application!
I suggest using a variable static long
and using Interlocked.Increment which handles concurrency and synchronization so you can assign Id to your objects easily. It is better than a GUID for debugging purposes and is more readable and uses less memory than a GUID.
//define an accessible static variable somewhere in your code
public static long __Id = 0;
//use it to assign unique Id to objects
UniqueID = Interlocked.Increment(ref __Id);
also its performance is better than GUID, here is a quick check and result
public static long __Id = 0;
private static void Main(string[] args)
{
var sw1 = new Stopwatch();
var guid = Guid.NewGuid();
sw1.Start();
for (var i = 0; i < 10000000; i++)
{
guid = Guid.NewGuid();
}
sw1.Stop();
Console.WriteLine(guid);
Console.WriteLine(sw1.ElapsedTicks);
var sw2 = new Stopwatch();
long id = 0;
sw2.Start();
for (var i = 0; i < 10000000; i++)
{
id = Interlocked.Increment(ref __Id);
}
sw2.Stop();
Console.WriteLine(id);
Console.WriteLine(sw2.ElapsedTicks);
}
and the result
f91419e0-9d3a-4e64-b7fd-ed2080dad599
10376104 (guide time)
10000000
304231 (long time) 34 times faster than guid
+3
source to share