StringReplace alternatives to improve performance

前端 未结 8 760
温柔的废话
温柔的废话 2021-02-04 12:46

I am using StringReplace to replace > and < by the char itself in a generated XML like this:

StringReplace(xml.Text,\'>\',\'>\',[rfReplaceA         


        
8条回答
  •  粉色の甜心
    2021-02-04 13:13

    The problem is that you are iterating the entire string size twice (one for replacing > by > and another one to replace < by <).

    You should iterate with a for and simply check ahead whenever you find a & for a gt; or lt; and do the immediate replace and then skipping 3 characters ((g|l)t;). This way it can do that in proportional time to the size of the string xml.Text.


    A simple C# example as I do not know Delphi but should do for you to get the general idea.

    String s = "<xml>test</xml>";
    char[] input = s.ToCharArray();
    char[] res = new char[s.Length];
    int j = 0;
    for (int i = 0, count = input.Length; i < count; ++i)
    {
        if (input[i] == '&')
        {
            if (i < count - 3)
            {
                if (input[i + 1] == 'l' || input[i + 1] == 'g')
                {
                    if (input[i + 2] == 't' && input[i + 3] == ';')
                    {
                        res[j++] = input[i + 1] == 'l' ? '<' : '>';
                        i += 3;
                        continue;
                    }
                }
            }
        }
    
        res[j++] = input[i];
    }
    Console.WriteLine(new string(res, 0, j));
    

    This outputs:

    test
    

提交回复
热议问题