Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options for uniquely identifying objects at runtime?

I need to attach a unique identifier to objects at runtime. The identifier must be unique for the duration of the application. I plan to do this my having a private member variable in the base class of my object model. This variable will be set at object initialization and the value will remain constant for the life of the object. No other object can have the same identifier for the duration of the application.

I can, of course, use a System.Guid, but that costs a 128 bits of storage for each object and I would like to consume fewer resources. I tried using an Int32 and initializing it with the System.Environment.TickCount property, but I don't get enough resolution and some objects wind up having the same value assigned.

The documentation for the TickCounter says that the TickCount property will roll to negative after ~29 and then back to zero in another 29 days. I would happly trade more resolution for a shorter roll over time.

Do I have other options that I don't know about?

like image 727
Michael J Avatar asked Jan 31 '11 17:01

Michael J


2 Answers

I would recommend using an integer value, and auto-incrementing it on assignment. You could use Interlocked.Increment to make this operation thread safe.

Most likely, a 32bit integer will be large enough for this task. I would recommend something like:

private static newObjectId = int.MinValue;

private static int GetNextId()
{
    return Interlocked.Increment(ref newObjectId);
}

You can then use that in your base class for assigning a new, unique identifier.

like image 140
Reed Copsey Avatar answered Nov 14 '22 09:11

Reed Copsey


To generate unique ids for objects you could use the aptly named ObjectIDGenerator that we conveniently provide for you:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.objectidgenerator.aspx

Note that, as the comment points out, the object id generator keeps a reference to the object alive, so it is only suitable for objects that you know are going to survive the life of the application anyway. If you intend to use this thing on more ephemeral objects then it is not a good solution.

You could build your own object ID generator that kept weak references if you wanted; it wouldn't be that difficult.

like image 10
Eric Lippert Avatar answered Nov 14 '22 09:11

Eric Lippert