Friday, March 8, 2013

c# - Contains vs IndexOf

I found that while searching for a special character in a given string,the contains performed better when the special character was at the beginning and IndexOf performance was better when the special character was at the end of the string.

string sString = "@MyRelativelySmallStringWithSpecialCharacter";
string sString = "MyRelativelySmallStringWithSpecialCharacter@";


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ContainsIndexOf

{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string sString = "MyRelativelySmallStringWithSpecialCharacterAtTheEnd@";
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();

                for (int i = 0; i < 1000000; i++)

                {
                    Console.Write("Iteration:" + i);
                    if (sString.IndexOf("@") != -1)
                        Console.WriteLine("Success !!!");
                }
                stopWatch.Stop();
                TimeSpan ts = stopWatch.Elapsed;

                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",

                    ts.Hours, ts.Minutes, ts.Seconds,
                    ts.Milliseconds);

                Stopwatch stopWatch1 = new Stopwatch();

                stopWatch1.Start();

                for (int i = 0; i < 1000000; i++)

                {
                    Console.Write("Iteration:" + i);

                    if (sString.Contains("@"))

                        Console.WriteLine("Success !!!");
                }

                stopWatch1.Stop();

                TimeSpan ts1 = stopWatch1.Elapsed;

                string elapsedTime1 = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",

                    ts1.Hours, ts1.Minutes, ts1.Seconds,
                    ts1.Milliseconds);

                Console.WriteLine("IndexOf RunTime " + elapsedTime);

                Console.WriteLine("Contains RunTime " + elapsedTime1);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}

Output

At the end









At the beginning



1 comment:

Anonymous said...

Here's a great blog which benchmarks several different C# techniques for testing if a substring occurs in a string, including the two you've described in your post:

http://blogs.davelozinski.com/curiousconsultant/csharp-net-fastest-way-to-check-if-a-string-occurs-within-a-string

_