vb.netperformancestringbuilderxml-literals

VB.NET XML Literals vs StringBuilder in term of performance


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()

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)