DateTimeFormatter is super slow

Andrew Leader 1 Reputation point
2020-01-25T00:16:12.877+00:00

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.

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Fay Wang - MSFT 5,221 Reputation points
    2020-01-27T02:12:04.72+00:00

    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

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.