Apps written in JavaScript occasionally need to obtain a UUID/GUID for one reason or another, so the question comes up: how to generate one?

One method is to just fabricate thestructureof a GUID with random numbers:

‘xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx’.replace(/[xy]/g, function (c) {
var r = Math.random()*16|0, v = c == < ‘x’ ? r : (r&0x3|0x8);
return v.toString(16);
});

The problem here is that uniqueness is not guaranteed. If you’re just using the identifier for some internal purpose, this method could work, but if you’re taking that GUID anywhere outside of your app, you run a possibility of collision with a properly-generated GUID.

The robust method is to use the Win32 CoGreateGuid() API that creates a GUID that is guaranteed to be unique. For this you need to write a small WinRT component as a wrapper, which, as I showed in Chapter 16 of my book, is actually quite easy and the resulting component (DLL/WinMD) is quite small. So while some have considered this a “heavyweight” solution, it’s actually not that heavy. Do note that CoCreateGuid, as a COM API, takes a little work to translate its result into a WinRT string (see this thread and this thread).

The same can be done through a C#/VB component with its NewGuid method, where the component would look like this:

public sealed class GuidProvider
{
public static String GetGuid()
{

Guid g = Guid.NewGuid();
return g.ToString();
}
}

The caveat with this, as I describe here, is that for even such a simple C# component, you’ll be pulling in the .NET runtime into your process, which significantly increases the memory overhead at runtime. So in the end, it’s better to use C++ for this purpose.

 


2 Comments

  1. Posted January 17, 2013 at 6:48 pm | Permalink

    Can you show an example of that GuidProvider class in C++ please? I failed to rewrite that class (apparently it can’t find the System namespace)