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?)
So the character array approach remains significantly faster although less so. In these tests, it was about 29% faster.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With