最近我有一個奇怪的性能問題。 我需要比較週期中的大量迭代的時間間隔。 我使用DateTime.TimeOfDay屬性來比較這些間隔。但是,我發現這些比較與DateTime比較相比非常慢。所以,我必須創建1年1個月和1天的DateTime,以加快時間間隔比較的速度。 我準備了一個小例子來展示我的意思。TimeSpan的對比很慢
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatesBenchmark
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
DateTime firstDate = DateTime.Now;
DateTime secondDate = DateTime.Now.AddSeconds(5);
for (int i = 0; i < 2000000; i++)
{
var a = firstDate.TimeOfDay > secondDate.TimeOfDay;
//var a = firstDate > secondDate;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadKey();
}
}
}
我爲15ms(如果在週期被註釋掉第一行)我的筆記本電腦與176毫秒(如果在週期第二行是註釋)。
我的問題很簡短。爲什麼?
你爲什麼在意?超過2百萬*記錄的176毫秒毫無用處。 –
這是簡化的例子。在我的真實應用程序中進行了大量的時間比較,我真的感受到了這種差異。 – eternity
176ms是構建高性能例程的大量時間,而200萬條記錄不是那麼多的數據。它是否重要*是一個完全不同的問題,但這不是一個微不足道的時間或不合理的數據量。 –