Is a timestamp in microseconds always unique?

前端 未结 2 571
失恋的感觉
失恋的感觉 2020-12-11 16:07

uniqid() in PHP generates a unique ID based on the current timestamp in microseconds. Is that really a foolproof way to generate a unique ID?

Even assuming there\'s

2条回答
  •  心在旅途
    2020-12-11 17:06

    Microsecond based ids are only guaranteed to be unique within limits. A single threaded scripts on a single computer is probably pretty safe in this regard. However, as soon as you start talking about parallel execution, be that simply on multiple CPUs within the same machine or especially across multiple machines, all bets are off.

    So it depends on what you want to use this id for. If you're just using it to generate an id which is used only within the same script, it's probably safe enough. For example:

    
    

    You very likely won't encounter any problems here with this limited use.

    However, if you start generating file names using uniqid or other such uses which are shared with other external scripts, I wouldn't rely on it. For filenames, using a hash based on the file contents may be a good idea. For general purpose decentralised randomly generated ids, UUIDs are a good fit (because they've been designed for this purpose).

提交回复
热议问题