最近、XML を生成するコードからパフォーマンスの問題が発生しました。ここで経験を共有することを考えました。少し長くなりますが、ご容赦ください。
いくつかの項目を含む単純な XML を用意します。各アイテムには 5 ~ 10 個の要素を含めることができます。構造は次のようなものです。
<Root>
<Item>
<Element1Key>Element1Val</Element1Key>
<Element2Key>Element2Val</Element2Key>
<Element3Key>Element3Val</Element3Key>
<Element4Key>Element4Val</Element4Key>
<Element5Key>Element5Val</Element5Key>
<Item>
<Item>
<Element1Key>Element1Val</Element1Key>
<Element2Key>Element2Val</Element2Key>
<Element3Key>Element3Val</Element3Key>
<Element4Key>Element4Val</Element4Key>
<Element5Key>Element5Val</Element5Key>
<Item>
</Root>
XML を生成するコードは (グローバル関数として簡略化された形式で) :
void addElement(std::string& aStr_inout, const std::string& aKey_in, const std::string& aValue_in)
{
aStr_inout += "<";
aStr_inout += aKey_in;
aStr_inout += ">";
aStr_inout += "Elemem1Val";
aStr_inout += "<";
aStr_inout += aValue_in;
aStr_inout += ">";
}
void PrepareXML_Original()
{
clock_t commence,complete;
commence=clock();
std::string anXMLString;
anXMLString += "<Root>";
for(int i = 0; i < 200; i++)
{
anXMLString += "<Item>";
addElement(anXMLString, "Elemem1Key", "Elemem1Value");
addElement(anXMLString, "Elemem2Key", "Elemem2Value");
addElement(anXMLString, "Elemem3Key", "Elemem3Value");
addElement(anXMLString, "Elemem4Key", "Elemem4Value");
addElement(anXMLString, "Elemem5Key", "Elemem5Value");
anXMLString += "</Item>";
replaceAll(anXMLString, "&", "&");
replaceAll(anXMLString, "'", "'");
replaceAll(anXMLString, "\"", """);
replaceAll(anXMLString, "<", "<");
replaceAll(anXMLString, ">", ">");
}
anXMLString += "</Root>";
complete=clock();
LONG lTime=(complete-commence);
std::cout << "Time taken for the operation is :"<< lTime << std::endl;
}
replaceAll() コードは、特殊文字をエンコードされた形式に置き換えます。これを以下に示します。
void replaceAll(std::string& str, const std::string& from, const std::string& to)
{
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos)
{
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
}
最小限の例では、200 個のアイテムをエンコードしました。しかし、実際の状況では、これはもっと多くなる可能性があります。上記のコードでは、XML の作成に約 20 秒かかりました。これは許容範囲をはるかに超えていました。何が問題なのですか?そして、ここでパフォーマンスを向上させる方法は?
注 : 文字列クラスの使用法には大きな違いはありません。MFC CString の別の文字列実装で同じロジックをテストしたところ、同様の (はるかに悪い) 観察結果が得られました。また、XML をより適切な方法で準備するために、ここでは DOM XML パーサーを使用したくありません。質問は XML に固有のものではありません。