没有人回答这个问题,因为结果可能会随着您使用的编译器和标准库而变化。例如,我把你的不同尝试集中到一个带有一点测试/时序线束的单个程序中。然后,只是为了好玩,我加入了第四次尝试(TEST3在下面的代码):
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <time.h>
#include <fstream>
#include <sstream>
#include <string.h>
static const int limit = 1000000;
void test1() {
std::ofstream test("test.xml");
for (int i = 0; i < limit; i++)
{
test << "<p> attr1=\"test1\" attr2=\"test2\" attr3=\"test3\" attr4=\"test4\">test5</p>\n";
}
test.close();
}
void test11() {
std::ofstream test("test.xml");
std::string fileDataStr;
for (int i = 0; i < limit; i++)
{
fileDataStr += "<p> attr1=\"test1\" attr2=\"test2\" attr3=\"test3\" attr4=\"test4\">test5</p>\n";
}
test << fileDataStr;
test.close();
}
void test2() {
std::ofstream test("test.xml");
std::stringstream fileDataStr;
for (int i = 0; i < limit; i++)
{
fileDataStr << "<p> attr1=\"test1\" attr2=\"test2\" attr3=\"test3\" attr4=\"test4\">test5</p>\n";
}
test << fileDataStr.str();
test.close();
}
void test3() {
std::ofstream test("test.xml");
std::vector<char> buffer;
char line [] = "<p> attr1=\"test1\" attr2=\"test2\" attr3=\"test3\" attr4=\"test4\">test5</p>\n";
size_t len = strlen(line);
buffer.reserve(limit * len + 1);
for (int i = 0; i < limit; i++)
std::copy(line, line + len, std::back_inserter(buffer));
test.write(&buffer[0], buffer.size());
test.close();
}
template <class T>
void timer(T f) {
clock_t start = clock();
f();
clock_t stop = clock();
std::cout << double(stop - start)/CLOCKS_PER_SEC << " seconds\n";
}
int main() {
timer(test1);
timer(test11);
timer(test2);
timer(test3);
}
然后我用VC++编译它,并得到了以下结果:
0.681 seconds
0.659 seconds
0.874 seconds
0.955 seconds
然后,我编译与G ++,并得到了这些结果:
1.267 seconds
0.725 seconds
0.795 seconds
0.649 seconds
第四个版本(我加的)给出了VC++中表现最差的,但与G ++最佳性能。 VC++速度最快的是(目前为止)g ++最慢的。
你在问为什么X是真的。不幸的是,X并不总是如此。
我们可能需要对确切的编译器和标准库进行相当详细的分析,以便给出一个真正意义重大的答案。
很明显,因为字符串处理正在进入图片,导致几个分配等 – P0W
我想在同等条件下做这个测试。我可以用指针而不是使用字符串连接来实现这一点,还是有其他方法? – aldebaran