0

Assume a simple collection of DateTime. I have for cycle in example 100000 iterations. In which inside Im calling collection.add(DateTime.NowUtc). Is it possible that some items in collection will be with the equal Ticks? In my database I need to save history of DateTime in order they created. Is it possible that two elements will have the same time and in database I can't determine which created first?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
TryHard
  • 125
  • 9
  • 3
    Yes, it is possible you will have collisions. See [Can using Ticks of DateTime.Now can generate duplicates unique identifiers?](https://stackoverflow.com/questions/65550289/can-using-ticks-of-datetime-now-can-generate-duplicates-unique-identifiers). – John Wu Jun 25 '23 at 08:54

2 Answers2

3

Why don't you carry out an experiment?

  for (int i = 0; i < 10_000_000; ++i) {
    // Or DateTime.Now
    var t1 = DateTime.UtcNow.Ticks;
    // Or DateTime.Now
    var t2 = DateTime.UtcNow.Ticks;

    if (t2 - t1 == 0) {
      Console.WriteLine($"Collision at {t1}");

      break;
    }
  }

I ran the code above and got

Collision at 638232836051899854

So collisions are quite possible at least at my workstation

If you want to have unique DateTime you can try adding 1 tick to the prior DateTime in case of (quite rare) collision:

DateTime prior = DateTime.MinValue;

for (int i = 0; i < 100_000; ++i) {
  DateTime now = DateTime.UtcNow;

  // In case of collision, let's assume that now is 1 tick after the prior
  if (now.Ticks <= prior.Ticks)
    now = new DateTime(prior.Ticks + 1, DateTimeKind.Utc);

  prior = now;

  ...
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

In theory yes it is possible, but in practice I think it is unlikely.

Even this code, will produce a different value:

var d1 = DateTime.Now;
var d2 = DateTime.Now;

Console.WriteLine($"d1 = {d1.Ticks}");
Console.WriteLine($"d2 = {d2.Ticks}");

Output

d1 = 638232802167319681

d2 = 638232802167372649

But if you want to be sure that you have a unique list then use HashSet, as it ensures only unique items.

Or if you use a normal List, then by default it has the order in which you insert items. So then the item with the lowest index value will be the one you created first.

But List orders can be modified, so this is not a guarantee.

Edit: But see the comment from

jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51