【发布时间】:2010-09-13 00:57:14
【问题描述】:
为了提高从文件读取的性能,我尝试将一个大(几 MB)文件的全部内容读入内存,然后使用 istringstream 访问信息。
我的问题是,读取这些信息并将其“导入”到字符串流中的最佳方式是什么?这种方法的一个问题(见下文)是,在创建字符串流时,缓冲区会被复制,内存使用量会加倍。
#include <fstream>
#include <sstream>
using namespace std;
int main() {
ifstream is;
is.open (sFilename.c_str(), ios::binary );
// get length of file:
is.seekg (0, std::ios::end);
long length = is.tellg();
is.seekg (0, std::ios::beg);
// allocate memory:
char *buffer = new char [length];
// read data as a block:
is.read (buffer,length);
// create string stream of memory contents
// NOTE: this ends up copying the buffer!!!
istringstream iss( string( buffer ) );
// delete temporary buffer
delete [] buffer;
// close filestream
is.close();
/* ==================================
* Use iss to access data
*/
}
【问题讨论】:
-
也许你应该搜索内存映射文件。
-
要记住的另一件事是文件 I/O 总是最慢的操作。 Luc Touraille 的解决方案是正确的,但还有其他选择。一次将整个文件读入内存将比单独读取快得多。
-
您喜欢复制数据。 1)复制到缓冲区。 2) 复制到匿名 std::string 中。 3)复制到iss。
标签: c++ optimization memory stream stringstream