Question

I've got a lot of VB code with StringBuilder. I'm considering changing them to XML Litterals, regards to performance is it faster than StringBuilder? Or it it slower?

This is an example of XML Literals:

Dim bookString = <bookstore xmlns="http://examples.books.com">
                       <book publicationdate=<%= publicationdate %> ISBN=<%= isbn %>>
                           <title>ASP.NET Book</title>
                           <price><%= price %></price>
                           <author>
                               <first-name><%= a.FirstName %></first-name>
                               <last-name><%= a.LastName %></last-name>
                           </author>
                       </book>
                   </bookstore>.Value

This is an example of using StringBuilder:

Dim stringBuilder = new StringBuilder()

stringBuilder.Append("<bookstore xmlns="http://examples.books.com">")
stringBuilder.Append("<book publicationdate=<%= publicationdate %> ISBN=<%= isbn %>>")
stringBuilder.Append("<title>ASP.NET Book</title>")
stringBuilder.Append("<price><%= price %></price>")
stringBuilder.Append("<author>")
stringBuilder.Append("<first-name><%= a.FirstName %></first-name>")
stringBuilder.Append("<last-name><%= a.LastName %></last-name>")
stringBuilder.Append("</author>")
stringBuilder.Append("</book>")
stringBuilder.Append("</bookstore>")

Dim bookString = stringBuilder.toString()
Was it helpful?

Solution

You should use XML literals simply to make sure your code is correct.
If you use StringBuilder, you are very likely to forget to escape something and generate invalid XML.

XML literals would probably be a little bit slower than pure strings, but it shouldn't make much difference.

If you're dealing with enormous files, you should use an XmlWriter that writes directly to disk or network; that should be faster than either one.

Note that in your specific example, ordinary string concatenation would be faster than a StringBuilder. (since you aren't using any loops)

OTHER TIPS

From a pure performance perspective, the best option is to test both alternatives. In addition to the other options already mentioned, you may want to consider the XStreamingElement to combine the type safety of Xml Literals (as compared to string concatenation/string builders) along with output streaming to limit the memory overhead. See http://msdn.microsoft.com/en-us/library/system.xml.linq.xstreamingelement.aspx for information on XStreamingElement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top