We have got an XMLIDList helper which uses += ( :( )
What I am looking for, what is the fastest possible way to do this? It is not been a problem before because the lists have been <10 items, but we have added a new feature that can pass 15k items. And as you can imagine, it is slow.
public static string EncodeGuidListToXML(IList<Guid> elementsToEncode)
{
if (elementsToEncode == null || elementsToEncode.Count == 0)
return String.Empty;
string beginItemNode = BeginItemNode;
string endItemNode = EndItemNode;
string xml = BeginRootNode;
foreach (Guid item in elementsToEncode)
{
xml += beginItemNode + item.ToString().ToUpper() + endItemNode;
}
xml += EndRootNode;
return xml;
}
The best way is not to use string concatenation to start with, IMO. Use an XML API. Build an XDocument
or an XmlDocument
, and then convert that to a string at the end. While your logic is reasonably simple at the moment, as soon as you start needing values which need escaping or anything like that, you really don't want to be replicating all the logic of a real XML API... so use an existing one.
Here's an example of how you might rewrite your current method:
public static string EncodeGuidListToXml(IList<Guid> guids)
{
if (elementsToEncode == null || elementsToEncode.Count == 0)
{
return "";
}
return new XDocument(
new XElement("Root",
guids.Select(guid => new XElement("Item", guid.ToString().ToUpper()))
)).ToString();
}
If you really want to stick to building strings directly, StringBuilder
is indeed the way to go.