为了将许多数据写入文件,我有两种方法:
直接逐个将数据写入 ofstream
ofstream file("c:\\test.txt"); for (int i = 0; i < 10000; ++i) { file << data[i]; }
先将数据写入istringstream,然后一次性将其写入ofstream
ostringstream strstream;
for (int i = 0; i < 10000; ++i)
{
strstream << data[i];
}
ofstream file("c:\\test.txt");
file << strstream.str();
不意外地,第二种方法更快,事实上,在我的HP7800机器上,它比第一种方法快4倍。但是为什么呢?我知道ofstream在内部使用filebuf,而ostringstream使用stringbuf-作为缓冲区,它们都应该驻留在内存中,因此不应该有任何区别。
底层有什么区别?
pubsetbuf()
。然后,您可以为流提供任何您认为合适的大小的缓冲区。我不确定是否存在除提供自定义大小的缓冲区之外的用例。 - sbi