我知道一种从流中读取并使用它的方法,如下所示:
strstream s; // It can be another standard stream type
// ...
while (!s.eof())
{
char buf[MAX];
s.read(buf, sizeof (buf));
int count = s.gcount();
THIRD_PARTY_FUNCTION(buf, count);
// ...
}
但是这段代码有一个滥用点,它首先从流中复制数据到buf
然后通过 buf
至 THIRD_PARTY_FUNCTION
.
有没有什么办法可以将代码改成下面的样子(我的意思是下面的代码避免了额外的复制)?
strstream s; // It can be another standard stream type
// ...
while (!s.eof())
{
char *buf = A_POINTER_TO_DATA_OF_STREAM(s);
int count = AVAIABLE_DATA_SIZE_OF_STREAM(s);
// Maybe it needs s.seekg(...) here
THIRD_PARTY_FUNCTION(buf, count);
// ...
}
最佳答案
这样的东西可能对你有用。
char buffer[2000];
std::istream& s = getStreamReference();
s.rdbuf()->pubsetbuf(buffer, 2000);
while(s)
{
THIRD_PARTY_FUNCTION(buffer, s.rdbuf()->in_avail());
s.ignore(s.rdbuf()->in_avail());
// Not sure this may go into an infinite loop.
// Its late here so I have not tested it.
}
请注意,我确实关心复制 2K 缓冲区的成本。
在我考虑进行这种优化之前,分析必须表明这是一个真正的热点,它会导致性能显着下降。在 99% 的情况下,可读性将是我最重要的因素。
关于使用流和缓冲区的 C++ 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14082026/