Erick Hate to say this but I'm afraid I don't agree with that. I think that Greg had probably got the most efficient method.
Greg uses a Replace followed by a string concatenation. That means he'll have to copy the string either once or twice: Twice if the call to String.Replace() needs to do anything, or just one allocation if the string contains no single quotes and the call to Replace() has no effect. By contrast, using a StringBuilder, you will always get at least two new string copy operations - one to copy the original string into the StringBuilder object, and another one to copy it back out again. Not only that, but your call to String.Replace() will give a third string copy if any single quotes do need to be replaced. Either way, using a StringBuilder gives one more string copy than Greg's method of manipulating the string. Simon --------------------------------------------------------------- Simon Robinson http://www.SimonRobinson.com --------------------------------------------------------------- ----- Original Message ----- From: "Erick Thompson" <[EMAIL PROTECTED]> To: <[EMAIL PROTECTED]> Sent: Friday, May 03, 2002 1:37 AM Subject: Re: [DOTNET] String concatenation performance > 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(); > } > > Erick > > ----- Original Message ----- > From: "Greg Gates" <[EMAIL PROTECTED]> > To: <[EMAIL PROTECTED]> > Sent: Thursday, May 02, 2002 5:24 PM > Subject: [DOTNET] String concatenation performance > > > > Hello everyone: > > > > I have the following helper method to format sql string parameters: > > > > public static string DoQuotes(string sqlParam) > > { > > if (sqlParam.IndexOf("'") > 0) > > { > > sqlParam = sqlParam.Replace("'","''"); > > } > > > > return "'" + sqlParam + "'"; > > } > > > > > > Is there a better way, performance-wise? > > > > thanks, Greg > > > > You can read messages from the DOTNET archive, unsubscribe from DOTNET, or > > subscribe to other DevelopMentor lists at http://discuss.develop.com. > > You can read messages from the DOTNET archive, unsubscribe from DOTNET, or > subscribe to other DevelopMentor lists at http://discuss.develop.com. > You can read messages from the DOTNET archive, unsubscribe from DOTNET, or subscribe to other DevelopMentor lists at http://discuss.develop.com.