Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 583
Ole Albers Avatar asked Apr 20 '16 08:04

Ole Albers


People also ask

Is String faster than char array?

So the character array approach remains significantly faster although less so. In these tests, it was about 29% faster.

Is String better than char?

C++ strings can contain embedded \0 characters, know their length without counting, are faster than heap-allocated char arrays for short texts and protect you from buffer overruns. Plus they're more readable and easier to use.

Is char faster than String C++?

Originally Answered: Which are faster in C++ either strings or char arr[]? If we talk of speed then string is faster, but it is convenient to use char array for better modification and operation.

Should I use char [] or STD string?

Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one. Save this answer.


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

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

like image 82
Dmitry Bychenko Avatar answered Oct 13 '22 03:10

Dmitry Bychenko