question

AndrewLeader-4158 avatar image
0 Votes"
AndrewLeader-4158 asked ·

DateTimeFormatter is super slow

Why is UWP's DateTimeFormatter so slow at formatting times to strings?

DateTimeFormatter.ShortTime.Format(time)

If you try formatting 1,440 different times in a loop, that loop takes 2.5 seconds to complete.

If you just use DateTime.ToString("t"), that same loop takes 0 seconds.

Since we seemingly have to use this DateTimeFormatter class to get properly localized times, it'd be nice if it performed reasonably.

uwp
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

FayWang-MSFT avatar image
0 Votes"
FayWang-MSFT answered ·

Hello,​

​Welcome to our Microsoft Q&A platform!

You could create a set of tasks that format times in an array. The tasks are stored in a List collection that is passed to the WhenAll(IEnumerable) method. When you call the Wait method, all the thread run synchronously, it will speed up operations. For example:

 Debug.WriteLine(DateTime.Now.ToString("hh:mm:ss.ff"));
 var tasks = new List();​
 for (int i = 0; i < 1440; i++) {​
     tasks.Add(Task.Run(() =>​
     {​
         DateTimeOffset dateAndTime = new DateTimeOffset(1970+i, 5, 1, 8, 6, 32,​
                                                  new TimeSpan(1, 0, 0));​
         DateTimeFormatter.ShortTime.Format(dateAndTime);​
     }));​
 }​
 Task t = Task.WhenAll(tasks);​
 t.Wait();​
 Debug.WriteLine(DateTime.Now.ToString("hh:mm:ss.ff"));

Output:

10:06:02.40

10:06:02.66

· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.