【发布时间】:2017-04-29 14:46:44
【问题描述】:
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
vector<char> f1()
{
ifstream fin{ "input.txt", ios::binary };
return
{
istreambuf_iterator<char>(fin),
istreambuf_iterator<char>()
};
}
vector<char> f2()
{
vector<char> coll;
ifstream fin{ "input.txt", ios::binary };
char buf[1024];
while (fin.read(buf, sizeof(buf)))
{
copy(begin(buf), end(buf),
back_inserter(coll));
}
copy(begin(buf), begin(buf) + fin.gcount(),
back_inserter(coll));
return coll;
}
int main()
{
f1();
f2();
}
显然,f1() 比f2() 更简洁;所以我更喜欢f1() 而不是f2()。但是,我担心f1() 的效率低于f2()。
所以,我的问题是:
主流 C++ 编译器会优化f1() 使其与f2() 一样快吗?
更新:
我使用了一个 130M 的文件在发布模式下进行测试(Visual Studio 2015 with Clang 3.8):
f1() 需要1614 毫秒,而f2() 需要616 毫秒。
f2() 比 f1() 快。
多么可悲的结果!
【问题讨论】:
-
哪个更快? - 应该测量。想到的一件事是
reserve需要vector的内存以避免重新分配 -
另外,可能值得考虑使用绳索,与输入库的选择没有直接关系,但无论如何:stackoverflow.com/questions/2826431/…
标签: c++ performance io compiler-optimization idioms