1

Is there a possibility for this code to generate the same identity,

for (int i = 0; i < 20; i++)
    {
        string TransID = DateTime.Now.Ticks.ToString();
    }

What are the considerations that make this happen?

sammer
  • 43
  • 6
  • 2
    if i understand your question correctly. can you check this question? They seem similar https://stackoverflow.com/questions/11849039/what-is-wrong-with-using-datetime-now-as-main-part-of-unique-id `Guid.NewGuid()` is a better way to achieve this. – Carbine Jan 03 '21 at 13:21

2 Answers2

2

Yes, this code can generate the same identifier.

Regardless of the tick precision, it can do so if the system date is changed in Windows and/or the Bios.

And also if it is run by computers in different time zones or if you travel.

The latter case implies that you should absolutely not use such a code even in local and not-connected applications.

If you need ID for a personnal and local application, and you never travel, this code does what you want, but it is not recommended to use such bad pattern.

As everyone says, without being wrong, you should use Guid.New() which is actually the safest standard, or an int or a long auto-increment (for local or managed by a server) for a better performance in some cases.

https://learn.microsoft.com/dotnet/api/system.datetime.now

https://en.wikipedia.org/wiki/Unique_identifier

https://en.wikipedia.org/wiki/Universally_unique_identifier

How expensive is a GUID cast and comparison vs a string comparison

0

First of all, let's define what is a tick. A single tick represents one hundred nanoseconds or one ten-millionth of a second.

1 second = 10 million ticks

Basically, if you don't generate two ID's at the same time, you're OK.

Also, I would suggest you to watch GUID as an alternative. It depends on what you are trying to accomplish.

this piece of code

for (int i = 0; i < 20; i++)
{
    string TransID = DateTime.Now.Ticks.ToString();
}

won't generate unique TransIDs on a computer which performs more than 10 million for loops per second.

Dorin Baba
  • 1,578
  • 1
  • 11
  • 23
  • At 4 GHz on a modern processor, how many instructions could be run in the time of a single tick? – Andrew Morton Jan 03 '21 at 14:13
  • One cycle per second is known as 1 hertz. This means that a CPU with a clock speed of 4 gigahertz (GHz) can carry out 4 thousand million (or 4 billion) cycles per second – Dorin Baba Jan 03 '21 at 14:15
  • 2
    Oh, I added my comment before your edit. It was intended to point out that "Basically, if you don't generate two ID's at the same time, you're OK." doesn't help with a modern processor. – Andrew Morton Jan 03 '21 at 14:18
  • 1
    My wooden PC generated 20 unique ID's ;)) That's why at first I forgot about that aspect – Dorin Baba Jan 03 '21 at 14:24