Performance char vs string

Just out of curiosity (not expecting a tangible result), which of the following codes is better for 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, and in the second, the lines in Contains () and Replace ()

Will the former have better performance due to less char memory, or will the latter work better because the compiler should not perform this operation?

(Or is it all nonsense because the CLR generates the same code in both cases?)

+4
source share
2 answers

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);

60 ms Char 500 ms String one (Core i5 3.2GHz, 64-bit,.Net 4.6), ,

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

9

+8

, , CLR .

: char , , : char , , .

. "" , .

0

All Articles