Greg Gates [mailto:[EMAIL PROTECTED]] wrote:

> I wrote the following routine to convert a datatable to a
> string. However, I am wondering if this is the most efficient
> way of doing it in .NET.
>
> private static string DataTableToString(DataTable table,
> string delimiter) {
>   if (table.Rows.Count == 0) {return String.Empty;}
>   StringBuilder buffer = new StringBuilder();
>
>   foreach (DataRow row in table.Rows)
>   {
>     object[] items = row.ItemArray;
>     foreach(object obj in items)
>     {
>       buffer.Append(obj.ToString());
>       buffer.Append(delimiter);
>     }
>
>   buffer.Remove(buffer.Length - delimiter.Length,delimiter.Length);
>   buffer.Append("\r");
>   buffer.Append("\n");
>   }
>
>   buffer.Remove(buffer.Length - 2,2);
>   return buffer.ToString();
> }

First, to take advantage of a JIT optimization, I would enumerate the
ItemArray using for instead of foreach, like so:

<codeSnippet language="C#">
object[] items = row.ItemArray;

for(int currentItemIndex = 0; currentItemIndex < items.Length,
currentItemIndex++)
{
  object item = items[currentItemIndex];

  buffer.Append(item.ToString());
  buffer.Append(delimiter);
}
</codeSnippet>

This avoids the overhead of IEnumerable and IEnumerator and allows the MSJIT
will optimize away bounds checking on the array.

Next, instead of calling Remove, set the Length instead, like so:

<codeSnippet language="C#">
buffer.Length = buffer.Length - delimiter.Length;
</codeSnippet>

Setting the Length truncates the buffer contents (note: this does *not*
affect the buffer's size), whereas Remove will actually do extra checking to
see if it should bring contents from one end of the buffer together with the
other end. For example, if the contents of the buffer were "hello" and you
called Remove(2, 2) you'd end up with "heo" where setting Length = 2 would
result in "he".

Finally, you can append the \r\n in one call instead of two. Other than
that... looks good.

HTH,
Drew
.NET MVP

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