3

I have noticed some code that I wrote a few years back and whilst thinking about optimizations I thought that this maybe an area that could be improved. I have the following:

var xml = new StringBuilder("");
foreach (var product in products)
{
xml.Append(product.AsXML());  // gives an xml string.
}
return String.Format("<products>{0}</products>", xml);

The xml string could be very large as the number of products in a database increase, I am wondering if there is a better way to do this.

JD

3
  • 1
    Obviously, the return line could avoid the string and be done on the StringBuilder (I would, for consistency's sake if nothing else). Commented May 11, 2011 at 12:28
  • Other than that, what need have you of keeping the whole thing as a String? Couldn't you be writing directly to a stream? Commented May 11, 2011 at 12:29
  • Originally there was a web service that the string would be passed to. That has been removed now. Would it be far faster or more memory efficient if I use a stream? Commented May 11, 2011 at 13:15

2 Answers 2

1

I would use Linq to XML link

You could try something like this:

    var prod = new List<string>();
    prod.Add("Apples");
    prod.Add("Oranges");
    var doc = new XElement("Product");
    foreach(String p in prod){


        doc.Add(new XElement("products", p));
    }

    Debug.WriteLine(doc.ToString());

outputs like this

<Product>
  <products>Apples</products>
  <products>Oranges</products>
</Product>

This mean you are no mucking around with Strings.

Cheers

Iain

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Iain, but unless I profile it, would it be any faster?
It would make tighter code, using an api designed for working with XML, but you looking at micro optimizing it, for very little gain.
1

The idiomatic way to represent that piece of code using LINQ to XML would look more like this:

var element = new XElement("products",
                  products.Select(p => XElement.Parse(p.AsXml())));

return element.ToString();

Though it is better suited for situations where you can represent the XML in memory. If not, I believe your best option is to use an XmlWriter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.