by
Neon Quach
24. September 2010 20:41
Sáng hôm nay mình đã đọc bài viết của Kirill Osenkov, viết về What’s faster: string.Equals or string.Compare? Sau đó mình code lại 1 chút trên nền .net 4.0 và thấy rỏ sự khác biết.
here is my code:
using System;
using System.Diagnostics;
namespace CS
{
class Program
{
static void Main(string[] args)
{
string strToCompare = "code2code";
Stopwatch sw = new Stopwatch();
sw.Start();
int result = String.Compare("code2code.info", strToCompare, StringComparison.OrdinalIgnoreCase);
sw.Stop();
Console.WriteLine(String.Format("String.Compare: {0}", sw.Elapsed));
sw.Reset();
sw.Restart();
bool bCompared = String.Equals("code2code.info", strToCompare, StringComparison.OrdinalIgnoreCase);
sw.Stop();
Console.WriteLine("String.Equal timer: {0}", sw.Elapsed);
Console.Read();
}
}
}
VB.NET
Module Module1
Sub Main()
Dim strToCompare As String = "code2code"
Dim sw As New Stopwatch()
sw.Start()
Dim result As Integer = String.Compare("code2code.info", strToCompare, StringComparison.OrdinalIgnoreCase)
sw.Stop()
Console.WriteLine(String.Format("String.Compare timer: {0}", sw.Elapsed))
sw.Reset()
sw.Restart()
Dim bCompared As Boolean = String.Equals("code2code.info", strToCompare, StringComparison.OrdinalIgnoreCase)
sw.Stop()
Console.WriteLine(String.Format("String.Equals timer: {0}", sw.Elapsed))
Console.ReadKey()
End Sub
End Module
Và kết quả là:

Như vậy String.Equals sẽ nhanh hơn 4x so với String.Compare.
Hope this help