编程语言
首页 > 编程语言> > C#:Guid.NewGuid()和DateTime.Now该选择哪个???

C#:Guid.NewGuid()和DateTime.Now该选择哪个???

作者:互联网

直接上代码:

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("正在计算Guid.....");

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            for (int i = 0; i < 10000000; i++)
            {
                Guid guid = Guid.NewGuid();
            }
            stopwatch.Stop();

            TimeSpan t = stopwatch.Elapsed;

            string totaltime = String.Format("{0:00}:{1:00}:{2:00}:{3:00}", t.Hours, t.Minutes, t.Seconds, t.Milliseconds);
            Console.WriteLine("使用Guid时,总用时:{0}", totaltime);//2s

            //----------------------------------------------------------------------------------//

            Console.WriteLine("正在计算DateTime.....");
            stopwatch.Start();

            for (int i = 0; i < 10000000; i++)
            {
                DateTime dateTime = DateTime.Now;
            }
            stopwatch.Stop();

            TimeSpan t2 = stopwatch.Elapsed;

            string totaltime2 = String.Format("{0:00}:{1:00}:{2:00}:{3:00}", t2.Hours, t2.Minutes, t2.Seconds, t2.Milliseconds);
            Console.WriteLine("使用DateTime时,总用时:{0}", totaltime2);//3s

            Console.ReadKey();
        }
    }
}

千万级别差一秒,再加一个零,差5s左右,所以用Guid比较合理!

 

标签:00,Console,C#,NewGuid,t2,DateTime,stopwatch,Guid
来源: https://www.cnblogs.com/stickcsharp/p/11204223.html