Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

c# - How expensive is a GUID cast and comparison vs a string comparison

which would be faster?

bool same=(Guid)Identifier==id;

bool same=String.Equals(string1,string2, StringComparison.OrdinalIgnoreCase);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I used this code:

object victim = Guid.Empty;
Guid target = Guid.NewGuid();

Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000000; i++){
    bool equal = ((Guid) victim) == target;
}
Console.WriteLine("Direct cast   : {0}", sw.Elapsed);

sw.Reset(); sw.Start();
for (int i = 0; i < 10000000; i++)
{
    bool equal = Guid.Equals(victim, target);
}
Console.WriteLine("Guid.Equals   : {0}", sw.Elapsed);

sw.Reset(); sw.Start();
string a = victim.ToString(); // as suggested by Mikael
string b = target.ToString();
for (int i = 0; i < 10000000; i++)
{
    bool equal = String.Equals(a, b, StringComparison.OrdinalIgnoreCase);
}
Console.WriteLine("String.Equals : {0}", sw.Elapsed);

Console.ReadLine();

And got this result for different values (best scenario):

object victim = Guid.Empty;
Guid target   = Guid.NewGuid();
// Direct cast   : 00:00:00.1164198
// Guid.Equals   : 00:00:02.1268147
// String.Equals : 00:00:00.4129527  // oh my!

And this result for same value (worse scenario)

object victim = Guid.Empty;
Guid target   = Guid.Empty;
// Direct cast   : 00:00:00.2793173
// Guid.Equals   : 00:00:03.5625948
// String.Equals : 00:00:01.7564302

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...