Search code examples
c#performancetypeschar

Performance char vs string


Just out of curiousity (not really expecting a measurable result) which of the following codes are better in case of performance?

private void ReplaceChar(ref string replaceMe) {
  if (replaceMe.Contains('a')) {
    replaceMe=replaceMe.Replace('a', 'b');
  }
}

private void ReplaceString(ref string replaceMe) {
  if (replaceMe.Contains("a")) {
    replaceMe=replaceMe.Replace("a", "b");
  }
}

In the first example I use char, while in the second using strings in Contains() and Replace()

Would the first one have better performance because of the less memory-consuming "char" or does the second perform better, because the compiler does not have to cast in this operation?

(Or is this all nonsense, cause the CLR generates the same code in both variations?)


Solution

  • If you have two horses and want to know which is faster...

      String replaceMe = new String('a', 10000000) + 
                         new String('b', 10000000) + 
                         new String('a', 10000000);
    
      Stopwatch sw = new Stopwatch();
    
      sw.Start();
    
      // String replacement 
      if (replaceMe.Contains("a")) {
        replaceMe = replaceMe.Replace("a", "b");
      }
    
      // Char replacement
      //if (replaceMe.Contains('a')) {
      //  replaceMe = replaceMe.Replace('a', 'b');
      //}
    
      sw.Stop();
    
      Console.Write(sw.ElapsedMilliseconds);
    

    I've got 60 ms for Char replacement and 500 ms for String one (Core i5 3.2GHz, 64-bit, .Net 4.6). So

     replaceMe = replaceMe.Replace('a', 'b')
    

    is about 9 times faster