将Guid与字符串进行比较

Ser*_*gan 9 c# string comparison guid

我很惊讶,我无法找到一个答案,这无论是在谷歌还是在这里SO,但什么是比较一个最好的方式stringGuid考虑的情况下,和,如果合适的话,性能

const string sid = "XXXXX-...."; // This comes from a third party library
Guid gid = Guid.NewGuid(); // This comes from the db

if (gid.ToString().ToLower() == sid.ToLower())

if (gid == new Guid(sid))

// Something else?
Run Code Online (Sandbox Code Playgroud)

更新: 为了使这个问题更加引人注目,我换sid一个const......因为你不能有一个Guid const,这是我处理的现实问题.

D S*_*ley 14

不要将Guids作为字符串进行比较,也不要Guid仅仅将字符串与现有字符串进行比较Guid.

除了性能之外,没有一种标准格式用于表示Guid字符串,因此您冒着比较不兼容格式的风险,您必须通过配置String.Compare执行此操作或将每个格式转换为小写来忽略大小写.

更常用和高效的方法是Guid使用本机Guid相等性从常量字符串值和所有比较创建静态,只读:

const string sid = "3f72497b-188f-4d3a-92a1-c7432cfae62a";
static readonly Guid guid = new Guid(sid);

void Main()
{
    Guid gid = Guid.NewGuid(); // As an example, say this comes from the db

    Measure(() => (gid.ToString().ToLower() == sid.ToLower()));
    // result: 563 ms

    Measure(() => (gid == new Guid(sid)));
    // result: 629 ms

    Measure(() => (gid == guid));
    // result: 10 ms

}

// Define other methods and classes here
public void Measure<T>(Func<T> func)
{
    Stopwatch sw = new Stopwatch();

    sw.Start();
    for(int i = 1;i<1000000;i++)
    {
        T result = func();
    }
    sw.Stop();

    Console.WriteLine(sw.ElapsedMilliseconds);
}
Run Code Online (Sandbox Code Playgroud)

因此,字符串比较和Guid从常量值创建新值比将常量值创建Guid的静态只读值高50-60倍Guid.