Optimize the string. Format + replace

I have this function. Visual studio profile tagged line with line. The formatting was just as hot and I was spending most of my time.

How can I write this loop more efficiently?

    public string EscapeNoPredicate(string sz)
    {
        var s = new StringBuilder(sz);

        s.Replace(sepStr, sepStr + sepStr);
        foreach (char v in IllegalChars)
        {
            string s2 = string.Format("{0}{1:X2}", seperator, (Int16)v);
            s.Replace(v.ToString(), s2);
        }
        return s.ToString();
    }

      

+2


a source to share


2 answers


Instead of evaluating s2s foreach v every time this method is called; you can keep them pre-calculated. Of course, I assume the IllegalChars and seperator remain the same.



+1


a source


  • You can put objects in string.format, so (Int16) v is not required. You can put "v"


0


a source







All Articles