최근에 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;
}
인코딩과 특수 문자를 대체 할 완전히 대체하기() 코드 형태. 아래에 나와 있습니다.
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과 관련이 없습니다.
실행 한 프로파일 러의 출력은 무엇입니까? 병목 현상이 정확히 어디를 가리 킵니까? 배당? 데이터 사본? – PlasmaHH
@PlasmaHH : 프로파일 러를 사용하지 않았지만, 함수 발생 시간대에서 각 항목 추가에 시간이 걸릴 것이라고 결론을 내릴 수있었습니다. 아래 답변을 참조하십시오. 아래 수정을 통해 성능을 획기적으로 향상시킬 수있었습니다. – PermanentGuest