Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Very strange. My "SubstringThenTrim" code is much slower than what it is supposed to be

$
0
0

I want to improve the performance of code like the following,

.Substring.Trim Approach

var str = "                abc       def         ";
return str.Substring(5, 10).Trim(); //*

I want to improve the performance of line * by the following new extension method on System.String.

        public unsafe static string FastSubstringThenTrim(this string str, int startIndex, int length)
        {
            var endIndex = startIndex + length - 1;

            while (startIndex <= endIndex)
            {
                if (!char.IsWhiteSpace(str[startIndex])) break;++startIndex;
            }

            while (endIndex >= startIndex)
            {
                if (!char.IsWhiteSpace(str[endIndex])) break;
                --endIndex;
            }

            return str.Substring(startIndex, endIndex - startIndex + 1);
        }

and then the first code piece can be rewritten as

.FastSubstringThenTrim Approach

var str = "                abc       def         ";
return str.FastSubstringThenTrim(5, 10); //**

The FastSubstringThenTrim method is written in a way exactly the same as .NET's build-in Trim method, and it reduces internal substring operations from twice to once. It should be faster,but actually it is slower by 20%. I don't know why and I have been stumbled on this issue for entire one day.

The following is the source code of .NET's official String.Trim method.

[SecuritySafeCritical] private string TrimHelper(int trimType) { int end = this.Length - 1; int start = 0; if (trimType != 1) { start = 0; while (start < this.Length) { if (!char.IsWhiteSpace(this[start]) && !IsBOMWhitespace(this[start])) { break; } start++; } } if (trimType != 0) { end = this.Length - 1; while (end >= start) { if (!char.IsWhiteSpace(this[end]) && !IsBOMWhitespace(this[start])) { break; } end--; } } return this.CreateTrimmedString(start, end); }

[SecurityCritical]
private string CreateTrimmedString(int start, int end)
{
    int length = (end - start) + 1;
    if (length == this.Length)
    {
        return this;
    }
    if (length == 0)
    {
        return Empty;
    }
    return this.InternalSubString(start, length);
}





Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>