Skip to content

Move away from Guid.NewGuid().ToString() for unique string id #72

Description

@ipjohnson

While Guid.NewGuid does generate a completely unique id, it's 36 characters long. This makes hashing and equality comparisons take longer.

The reality is we only need uniqueness within the process space and make a good faith effort to avoid collisions with user saved extra data.

With that in mind I'm going to introduce the following class that will generate unique id's that are 4characters + N (number always incrementing)

public static class UniqueStringId
{
        private static ThreadLocal<Random> _local = new ThreadLocal<Random>(() => new Random());
        private static int _counter;

        public static string Generate()
        {
            var intValue = _local.Value.Next();

            StringBuilder builder = new StringBuilder();

            builder.Append((char)(intValue % 95 + 32));
            intValue = intValue >> 7;
            builder.Append((char)(intValue % 95 + 32));
            intValue = intValue >> 7;
            builder.Append((char)(intValue % 95 + 32));
            intValue = intValue >> 7;
            builder.Append((char)(intValue % 95 + 32));
            builder.Append(Interlocked.Increment(ref _counter));

            return builder.ToString();
        }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions