Erick Thompson [mailto:[EMAIL PROTECTED]] wrote:

> This should be faster. I'm not sure about the Insert method
> as far as performance goes but this method shouldn't cause
> any unneeded string allocations. However, I'm sure it could
> be improved on.
>
> public static string DoQuotes(string sqlParam) {
>     System.Text.StringBuilder sb = new
> System.Text.StringBuilder(sqlParam.Length + 2);
>     if (sqlParam.IndexOf("'") > 0) {
>         sb.Insert(2,sb.Replace("'", "''").ToString());
>     } else {
>         sb.Insert(2, sqlParam);
>     }
>     sb.Insert(1, "'");
>     sb.Append("'");
>     return sb.ToString();
> }

Actually, here's how I'd do it... with explanation following:

<codeSnippet language="C#">
public static string EscapeSqlQuotes(string value)
{
        return value.Replace("'", "''");
}
</codeSnippet>

Easy right? Here's why you want to use just this:

It does away with the call to IndexOf which Replace needs to do internally
anyway. If there's no matches found Replace scanned the string just as
IndexOf would have anyway, except if there are any matches it actually
replaces them. In the case where there is one or more matches you wasted
cycles scanning once with IndexOf. Here's the important factor in this
approach and why this approach is a win win: if the string doesn't contain a
match and no replacements are made, the same string instance is returned,
which means there's no new allocation at all!

Here's a simple snippet of code you can use to prove this:

<codeSnippet langauge="C#">
string test = "hello world";
string result = test.Replace("'", "''");

Debug.WriteLine(String.Format("{0}", Object.ReferenceEquals(test, result)));
</codeSnippet>

Later,
Drew

You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to