performance – Replace C# String.Substring

performance – Replace C# String.Substring

The problem with your function is that you are returning the substring… Therefore, I dont see the way to avoid constructing a new string.

The next question is what exactly are you doing with the result? Maybe you could change the signature of the get_element method, e.g. to receive a StringBuilder and then to copy characters from the target string instead of building the new string.

public void get_element(int element_number, StringBuilder buffer)
{
    ...
    //  instead of: return line_text.Substring(...); 
    buffer.Append(line_text, start_index, end_index - start_index);
}

Anyway, cost of constructing new strings is not too high. Maybe there are other reasons why performance is poor in your case. Maybe you are doing too many concatenations of strings returned by this method?

I doubt the problem is caused by the bounds checking inside the Substring method.

But if you want to be sure and unsafe code is allowed, you can try the following string constructor:

public unsafe String(
    char* value,
    int startIndex,
    int length
)

like this:

public static class StringUtils
{
    public static unsafe string UnsafeSubstring(this string source, int startIndex, int length)
    {
        fixed (char* chars = source)
            return new string(chars, startIndex, length);
    }
}

Then replace Substring calls with UnsafeSubstring and see if there is any noticeable difference.

performance – Replace C# String.Substring

A string is only an array of char. You could loop through the char array between your known bounds and replace the char.

Leave a Reply

Your email address will not be published. Required fields are marked *