0

What is best approach out of below options:

option 1: var d = new Date(); uniqueString = d.getTime();

option 2: uniqueString = Math.random();

Farhat Naz Biya
  • 105
  • 1
  • 10
  • 2
    Related: [Create GUID / UUID in JavaScript?](http://stackoverflow.com/q/105034/1529630) – Oriol Feb 21 '16 at 18:29
  • "Out of below options": I think it would be a combination of both. – Nicensin Feb 21 '16 at 18:30
  • 2
    None of those will be terribly unique. – SLaks Feb 21 '16 at 18:31
  • This is true but he asked for the best solution based on his two options. Real uniqueness is not given; you are right. – Nicensin Feb 21 '16 at 18:34
  • 2
    Please add more detail on your definition of "unique". Are you looking for a session id? A primary key for a database? A request id you can use to correlate requests and responses? Depending on what you're trying to do, either or neither would work. In a vacuum I wouldn't use either of the above. – Chris Tavares Feb 21 '16 at 18:35
  • 1
    @Nicensin Thing is, they might not even be "unique enough." If `Math.random()` returns a 64-bit floating-point `double`, your chance of collisions becomes about (https://www.wikiwand.com/en/Birthday_attack) 1-in-a-million after 6 million generated keys. If the scope of the key is transient, this might be good enough. If you're storing an audit log for a largeish web application, it probably won't. – millimoose Feb 21 '16 at 18:51

2 Answers2

1

It is possible (however unlikely) that by using dates (sequential, not random) that two different instances could coincide.

The odds of an overlap from Math.random() are much lower (again possible, however unlikely).

S.Pote
  • 71
  • 1
  • 5
  • 3
    It's not super unlikely for timestamps to coincide. If you're generating two without any long-running operation inbetween, sooner or later processors could get fast enough for the two successively generated timestamps to be the same. – millimoose Feb 21 '16 at 18:37
  • But there is a chance Math.random() be returning same string when used at different times. – Farhat Naz Biya Feb 22 '16 at 08:32
  • Coinciding times is statistically more likely (and as millimoose wisely points out, getting more likely as processor speeds increase) than Math.random(). As emdevtec states you get greater decimal precision (Date is only to a millisecond and then not random but sequential, random is 16 decimal places, all of which are randomized) – S.Pote Feb 22 '16 at 12:44
1

Out of the two I would go for the second option.

While getTime() would yield 13 digits, most of them being constant in a period of weeks, random() would randomize a number with about 16 digits.

Note that if by numeric you mean digits only, then you would have to work a little more to get rid of the 0. part of the randomized number.

guysigner
  • 2,822
  • 1
  • 19
  • 23