将Guid与字符串进行比较

时间:2016-06-27 21:39:25

标签: c# string comparison guid

我很惊讶我无法在Google或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?

更新 为了使这个问题更具吸引力,我将sid更改为const ...因为您无法Guid const这是我正在处理的真正问题。< / p>

2 个答案:

答案 0 :(得分:15)

不要将Guid作为字符串进行比较,也不要在字符串中创建新的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);
}

因此,字符串比较和从常量值创建新Guid比将Guid与从常量创建的静态只读Guid进行比较要贵50-60倍值。

答案 1 :(得分:-1)

详细介绍D Stanley

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

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

    Measure(() => (gid.ToString().ToLower() == sid.ToLower()));
    // result: 177 ms
    Measure(() => (gid == new Guid(sid)));
    // result: 113 ms
    Measure(() => (gid == guid));
    // result: 6 ms
    Measure(() => (gid == Guid.Parse(sid)));
    // result: 114 ms
    Measure(() => (gid.Equals(sid)));
    // result: 7 ms

}

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

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

    Console.WriteLine(sw.ElapsedMilliseconds);
}

因此,如果您不能将guid存储在一个常量中,则最好使用内置的Guid.Equals()。