我想知道的性能开销是多少
string line, word;
while (std::getline(cin, line))
{
istringstream istream(line);
while (istream >> word)
// parse word here
}
我认为这是标准c++
标记化输入的方法。
具体来说:
- 每行是否复制了三次,首先通过
getline
, 然后通过istream
构造函数,最后通过operator>>
每个词? - 会经常 build 和破坏
istream
成为问题?如果我定义istream
的等效实现是什么在外层之前while
循环?
谢谢!
更新:
等效的实现
string line, word;
stringstream stream;
while (std::getline(cin, line))
{
stream.clear();
stream << line;
while (stream >> word)
// parse word here
}
将流用作本地堆栈,压入行并弹出单词。 这样就可以摆脱之前版本中可能频繁调用构造函数和析构函数,利用流内部缓冲的作用(这个点对吗?)。
替代解决方案,可能是扩展 std::string 以支持 operator<<
和 operator>>
,或扩展 iostream 以支持某事。喜欢locate_new_line
. 在这里集思广益。
最佳答案
不幸的是,iostreams 不适用于性能密集型工作。问题不是在内存中复制东西(复制字符串很快),而是虚函数调度,可能与每个字符的多个间接函数调用有关。
至于你关于复制的问题,是的,当你初始化一个新的 stringstream
时,所有的东西都会被复制。 (字符也通过 getline
或 >>>
从流复制到输出字符串,但这显然无法阻止。)
使用 C++11 的移动
工具,您可以消除多余的拷贝:
string line, word;
while (std::getline(cin, line)) // initialize line
{ // move data from line into istream (so it's no longer in line):
istringstream istream( std::move( line ) );
while (istream >> word)
// parse word here
}
总而言之,只有当测量工具告诉您性能是一个问题时,性能才是一个问题。 Iostreams 灵活且健壮,filebuf
基本上足够快,因此您可以对代码进行原型(prototype)设计以使其正常工作,然后优化瓶颈而无需重写所有内容。
关于c++ - 通过 istringstream 的 c++ 字符串标记化的性能开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10961224/