Register
Sunday, February 05, 2012
 
 DBAs And ProgrammersBlog
  
News! Minimize
   
 
 Print   
 
Misc Blog Stuff Minimize
   
 
 Print   
 
The Reluctant DBA Minimize
 
 
 
 Print   
 
Reluctant DBA Minimize
   
 
  
 
Reluctant DBA Minimize
   
 
  
 
The Reluctant DBA Minimize
 
Aug19

Written by:CarpDeus
8/19/2008 3:51 PM 

Well, that really depends on how the input comes in. But if you need to validate whether a string is a UUID, there are a couple of ways to do that.

First is by trying to convert the string to a UUID and catching the error.

 private bool IsValidGUID(string GUIDCheck)
  {
   bool retVal = false;
   try  to convert the string to a guid
   {
    Guid g = new Guid(GUIDCheck);
     We successfully converted it, return true
    retVal = true;
   }
   catch (System.FormatException)   The string was not in a GUID format
   { retVal = false; }
   catch (Exception ex)  Something else went wrong, let the caller figure it out
   { throw ex;  }
   return retVal;
  }

The downside to this is that throwing errors can be expensive. A better version is to RegEx it (original source, Andrew Gunn), simplified here:

private bool IsValidGUID(string GUIDCheck)
  {
   if (!string.IsNullOrEmpty(GUIDCheck))
   {
    return new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$").IsMatch(GUIDCheck);
   }
   return false;
  }

Note: My only change is not using a variable.

So, how much faster is it? A simple test that processed 50 valid and 50 invalid UUIDs 100 times showed the following times:

  • RegEx Average to process 50 valid/50 invalid UUIDs:     5.85 ms
  • Catch Average to process 50 valid/50 invalid UUIDs: 493.17 ms

That's not even including the memory costs involved in using a Catch nor the aborted threads.

That's today's lesson, RegEx is better.

Josef

PS... Source for the test available if you want it.

Tags:

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment  Cancel 
 
 
  
 
Privacy Statement | Terms Of Use Copyright 2001-2008 by ReluctantDBA.com