Xmlドキュメントを作成するときにメモリを割り当てすぎないようにするための最善の解決策を見つけようとしています。可能な限り少ないリソースでかなり大きなXmlを構築する必要があります(Webサービスは1秒あたり数百の呼び出しを処理できる必要があります)。Xml自体の構造はあまり変わりませんが、データは一貫して変化します。私の現在のソリューションはXDocumentとXElement(LINQ)です。以下は、私が今日行っていることの簡単なサンプルです。
static Stream GetXml(string d1, string d2, string d3)
{
XElement x =
new XElement("myElement",
new XElement("myOtherElement1", d1),
new XElement("myOtherElement2", d2),
new XElement("myOtherElement3", d3));
// ... more XElement
// ... return Stream
}
Xmlドキュメントが大きくなりすぎると、XDocumentと何百ものXElementをインスタンス化すると非常にコストがかかり、1秒あたりの呼び出し数が減少します。私は現在、オブジェクトをインスタンス化せずに文字列(XElement)を単純にストリーミングするある種のテンプレートエンジンを作成することを考えています。どのようにそれをしますか?それは正しいことですか?
static Stream GetXml(string d1, string d2, string d3)
{
const string xml = @"
<myElement>
<myOtherElement1>{0}</myOtherElement1>
<myOtherElement2>{1}</myOtherElement2>
<myOtherElement3>{2}</myOtherElement3>
</myElement>";
// What's the best way to {0}, {1}, {2} without allocating
// objects and using as little RAM as possible. I cannot
// use string.Format since it allocates strings.
StreamWriter sw = new StreamWriter(stream);
sw.Write(xml);
}