Quantcast String.Compare và String.Equals cái nào tối ưu trong .net 4.0

String.Compare và String.Equals cái nào tối ưu trong .net 4.0

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

Tags: , , ,


Categories: visual studio 2010 | c# | vb.net

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at devinition.com and also a Microsoft Certified Technology Specialist (MCTS), Microsoft Certified Professional Developer (MCPD) in Net Framework 2.0 and 3.5: Web Applications and MCTS .NET Framework 3.5, ADO.NET Applications

Powered by BlogEngine.NET 2.5.0.5 - Eco Theme by n3o Web Designers