Search code examples
c#stringperformancecontainsindexof

Performance of IndexOf(char) vs Contains(string) for checking the presence of a character in a string


I want to know if

string.IndexOf(char) 

is faster than

string.Contains(string) 

Intention is to check if a single character is present in a string. I know that as per requirement I should use string.Contains(string) but that is not the point of this question. I did try to disassemble mscorlib.dll in an attempt to compare their implementations but I could not find the implementation of

 string.IndexOf(char)

as it is implemented within the CLR itself. Implementation of

 string.Contains(string)

looks quite heavy though.


Solution

  • Just test and see

      String source = new String('a', 10000000) + "b" + new String('c', 10000000);
    
      Stopwatch sw = new Stopwatch();
    
      sw.Start();
    
      // Just an estimation
      int result = source.IndexOf('b');
      // int result = source.IndexOf("b");
      // Boolean result = source.Contains("b");
      // Boolean result = source.Contains('b');
    
      sw.Stop();
    
      int time = sw.ElapsedMilliseconds;
    

    At my workstation (i5 3.2 GHz, .Net 5.0 64 bit) it takes about 10 ms for Char and 38 ms for String

    Edit: Performance's outcome is

      IndexOf(Char)     10 -- Fastest
      IndexOf(String)   38 
      Contains(Char)   100 -- Slowest
      Contains(String)  41
    

    so IndexOf(String) and Contains(String) are roughly the same