Generating Unique Strings (Ids) in JavaScript

Well, there are tools in JavaScript that allow you to create unique ids or strings.

I will be using to two ideas to create these unique strings.

Method 1: Memoization

The idea is to generate some random string and checking if it has already been generated the recursively generate another one and test again. If the generated string has not been already generated, then simply cache it somewhere and return it to the calling function.

Here is an example of it:

function getUniqueId() {
    getUniqueId.cache = getUniqueId.cache ? getUniqueId.cache : [];
    var randomString = "ID" + Math.random().toString().substr(2);
    if(getUniqueId.cache.indexOf(randomString) === -1) {
        getUniqueId.cache.push(randomString);
        return randomString;
    } else {
        return getUniqueId();
    }
}

Method 2: Closure
Closures are on of the coolest things available in JavaScript. Closures allow us to access local variables of a function when you are out of he scope of the function.
Doesn’t it sound a little crazy: “How can a local variable of a function can be accessed while we are not in the scope of that function i.e., the variable is out of the current scope!”.

Well its true that we cannot access the out of the scope variable of a function, But the variables and functions local to that variable can access it right. This is the concept we will be using to generate our unique Id or string.

Here it is.

    var getUniqueId = (function () {
        var local = 0;
        return function () {
            return local++;
        }
    })();

In the function above we are returning a reference to a local function, for which the variable local is in the scope and can still increment it. So every time we call the getUniqueId function actually the inner function also gets called and every time we get the incremented value.

Issues with these approaches:

Both of the above concepts are pretty cool to use, but you know nothing comes for free. Both have some performance and memory(space) issues with them.

If we carefully analyze the situation when we use closures, we are accessing an out of scope function and we all know that accessing out of scope variables is much costlier as compared to accessing local variables and functions in terms of performance as JavaScript engine has to search for the variable which is sitting far-far away from the current scope.
The situations worsens if the function has been defined in the global scope, because we have to go all the way to the global scope to get it.

Now if we take a look at the Memoization approach, we will see as the list of cached items increases, the function will tend to slow down. This slowness is because of the fact that before returning the the generated string, it has to traverse the whole cache. This slowness increases as the size of the cache grows.

There are some memory issues too with theses approaches because we in case of Memoization are maintaining a cache and in case of Closure the JS engine has to preserve a whole scope and its members.

So using these tool with care is necessary or our program would run into other issues.

PS: Lets get lazy a bit
Now here is the laziest(and easiest) way to generate unique strings:
 
Date/Time

function getUniqueId(padding) {
   return padding + (new Date()).getTime();
}

 
I hope this last function is very self explainatory.

Advertisements

One thought on “Generating Unique Strings (Ids) in JavaScript

  1. Pingback: Better use of Memoization JavaScript | Randomly Picked

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s