C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Further we benchmark these methods to see a performance difference.
Example. This program benchmarks the GetLastWriteTime and GetLastWriteTimeUtc methods. Often these two methods are interchangeable in programs. We first call each method on the target file to prime the disk cache. Then we measure the performance.
C# program that uses File.GetLastWriteTimeUtc using System; using System.Diagnostics; using System.IO; class Program { static void Main() { const int m = 10000; File.GetLastWriteTime("C:\\deves.txt"); File.GetLastWriteTimeUtc("C:\\deves.txt"); var s1 = Stopwatch.StartNew(); for (int i = 0; i < m; i++) { DateTime d = File.GetLastWriteTime("C:\\deves.txt"); } s1.Stop(); var s2 = Stopwatch.StartNew(); for (int i = 0; i < m; i++) { DateTime d = File.GetLastWriteTimeUtc("C:\\deves.txt"); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / m).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / m).ToString("0.00 ns")); Console.Read(); } } Output 30345.84 ns 27041.65 ns
We can see from this simple program that GetLastWriteTimeUtc is the faster method. It is about 10% faster. I discovered this in IL Disassembler. Internally GetLastWriteTime simply calls into GetLastWriteTimeUtc and then calls ToLocalTime.
Thus: If you do not need a local time, GetLastWriteTimeUtc (with the UTC) is faster.
Discussion. The performance difference between GetLastWriteTime and GetLastWriteTimeUtc will apply also to several other methods. The File type itself, and the FileInfo type, both contain methods that can optionally be called without the UTC suffix.
Method list File.GetCreationTime File.GetCreationTimeUtc File.GetLastAccessTime File.GetLastAccessTimeUtc File.GetLastWriteTime File.GetLastWriteTimeUtc FileInfo.CreationTime FileInfo.CreationTimeUtc FileInfo.LastAccessTime FileInfo.LastAccessTimeUtc FileInfo.LastWriteTime FileInfo.LastWriteTimeUtc
Summary. We called both File.GetLastWriteTime and GetLastWriteTimeUtc. The latter method is more efficient because it does less. The FileInfo type has LastWriteTime and LastWriteTimeUtc properties. These are the same as the two methods shown.