Guid.Parse() or new Guid() - What's the difference?

后端 未结 5 1477
悲哀的现实
悲哀的现实 2020-12-29 19:24

What is the difference between these two ways of converting a string to System.Guid? Is there a reason to choose one over the other?

var myguid          


        
5条回答
  •  星月不相逢
    2020-12-29 19:45

    I tried performance on one milion guids and Guid.Parse seems to be a insignificantly faster. It made 10-20 milisecods difference of 800 miliseconds of total creation on my PC.

    public class Program
    {
        public static void Main()
        {
            const int iterations = 1000 * 1000;
            const string input = "63559BC0-1FEF-4158-968E-AE4B94974F8E";
    
            var sw = Stopwatch.StartNew();
            for (var i = 0; i < iterations; i++)
            {
                new Guid(input);
            }
            sw.Stop();
    
            Console.WriteLine("new Guid(): {0} ms", sw.ElapsedMilliseconds);
    
            sw = Stopwatch.StartNew();
            for (var i = 0; i < iterations; i++)
            {
                Guid.Parse(input);
            }
            sw.Stop();
    
            Console.WriteLine("Guid.Parse(): {0} ms", sw.ElapsedMilliseconds);
        }
    }
    

    And output:

    new Guid(): 804 ms

    Guid.Parse(): 791 ms

提交回复
热议问题