Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is String.Substring more efficient than String.Split?

Tags:

c#

.net

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?

like image 867
Eric Dunaway Avatar asked Feb 16 '23 17:02

Eric Dunaway


1 Answers

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.

like image 101
RenniePet Avatar answered Feb 18 '23 05:02

RenniePet