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

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

 var myguid = Guid.Parse("9546482E-887A-4CAB-A403-AD9C326FFDA5"); 

or

 var myguid = new Guid("9546482E-887A-4CAB-A403-AD9C326FFDA5"); 
+47
c # guid
Aug 02 '11 at 17:23
source share
4 answers

A quick glance at the reflector shows that both are pretty much equivalent.

 public Guid(string g) { if (g == null) { throw new ArgumentNullException("g"); } this = Empty; GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.All); if (!TryParseGuid(g, GuidStyles.Any, ref result)) { throw result.GetGuidParseException(); } this = result.parsedGuid; } public static Guid Parse(string input) { if (input == null) { throw new ArgumentNullException("input"); } GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (!TryParseGuid(input, GuidStyles.Any, ref result)) { throw result.GetGuidParseException(); } return result.parsedGuid; } 
+60
Aug 02 '11 at 17:27
source share

Use the most readable version. These two are implemented almost exactly the same.

The only real difference is that the constructor is initialized to Guid.Empty before trying to parse. However, the effective code is identical.

Moreover, if Guid comes from user input, then Guid.TryParse will be better than any option. If this Guid hardcoded and always valid, any of the above options is perfectly reasonable.

+18
Aug 02 '11 at 17:27
source share

I have tried working on one million and Guid.Parse seems insignificant faster. This made 10-20 milisecods a difference of 800 milliseconds 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 the conclusion:

new guid (): 804 ms

Guid.Parse (): 791 ms

+9
Jul 10 '13 at 12:07 on
source share

I would go with TryParse . This is no exception.

+4
Aug 02 '11 at 17:25
source share



All Articles