Fix string for javascript in c #

I have a function that fixed non-printable characters in C # for JavaScript. But it works very slowly! How to increase the speed of this function?

private static string JsStringFixNonPrintable(string Source)
    {
        string Result = "";
        for (int Position = 0; Position < Source.Length; ++Position)
        {
            int i = Position;
            var CharCat = char.GetUnicodeCategory(Source, i);
            if (Char.IsWhiteSpace(Source[i]) ||
                CharCat == System.Globalization.UnicodeCategory.LineSeparator ||
                CharCat == System.Globalization.UnicodeCategory.SpaceSeparator) { Result += " "; continue; }
            if (Char.IsControl(Source[i]) && Source[i] != 10 && Source[i] != 13) continue;
            Result += Source[i];
        }
        return Result;
    }
+3
source share
3 answers

I transcoded a piece of code using a class StringBuilderwith a predefined buffer size ... which is much faster than your sample.

    private static string JsStringFixNonPrintable(string Source)
    {
        StringBuilder builder = new StringBuilder(Source.Length); // predefine size to be the same as input
        for (int it = 0; it < Source.Length; ++it)
        {
            var ch = Source[it];
            var CharCat = char.GetUnicodeCategory(Source, it);
            if (Char.IsWhiteSpace(ch) ||
                CharCat == System.Globalization.UnicodeCategory.LineSeparator ||
                CharCat == System.Globalization.UnicodeCategory.SpaceSeparator) { builder.Append(' '); continue; }
            if (Char.IsControl(ch) && ch != 10 && ch != 13) continue;
            builder.Append(ch);
        }
        return builder.ToString();
    }
+5
source

Instead of concatenating a string, try using System.Text.StringBuilderone that internally supports a character buffer and does not create a new object every time you add.

Example:

StringBuilder sb = new StringBuilder();
sb.Append('a');
sb.Append('b');
sb.Append('c');
string result = sb.ToString();
Console.WriteLine(result); // prints 'abc'
+1
source

All Articles