Joe Duffy's Blog implies using string.Substring
is more efficient than string.Split
.
I don't know if its saying the Substring
method does not allocate a new string or if it is just more efficient because it does not make any unneeded allocations. Can you please explain how it is more efficient and show an example.
I understand his first example as creating an array and then processing each of the strings in the array.
string str = ...;
string[] substrs = str.Split(',');
foreach (string subtr in substrs) {
Process(substr);
}
How is the following more efficient
string str = ...;
int lastIndex = 0;
int commaIndex;
while ((commaIndex = str.IndexOf(',', commaIndex)) != -1) {
Process(substr, lastIndex, commaIndex);
lastIndex = commaIndex + 1;
What I see is using String.IndexOf
to find the index of the comma then processing the string. I assume he intends to use String.Substring
to extract the data during his processing. One of the comments below suggested he may be pulling it character by character. Would he be pulling characters until he hits the next comma possibly building up an array of char?
Good grief.
Old joke: The manager wanted to know if programmer A or programmer B was the better programmer, so he staged a contest. They both were to write a program to solve a given complicated problem, and the one who wrote the best program would win.
The two programmers submitted their answers. Programmer A's program ran fastest, and the manager was about to declare him to be the winner when programmer B pointed out that the answer provided by programmer A's program was a bit off.
"But my program is still fastest, I deserve to win", said programmer A.
"If the answer doesn't have to be correct, I can write a program that is 10 times faster than yours", retorted programmer B.
Joe Duffy's second example, where he avoids using string.Split(), is wrong. It won't compile. The variable "substr" is undefined.
I rest my case.
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