views:

51

answers:

2

I have this function. The visual studio profile marked the line with string.Format as hot and were i spend much 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();
    }
+1  A: 

Instead of calculating s2s foreach v each time this method is called; you can store them precalculated. Of course I am assuming IllegalChars and seperator remains same.

tafa
and i was going to rewrite the loop to iterator sz instead. good idea.(i am glad to have fresh eyes on this one)
acidzombie24
A: 
  • In a string.format you can put objects, so (Int16)v is not needed. You can supply "v"
Ivo
That would give me the name and not the enum value. -edit- scratch that. the char (letter) and not the numerical value.
acidzombie24