I'm doing something really simple: slurping an entire text file from disk into a std::string
. My current code basically does this:
std::ifstream f(filename);
return std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
It's very unlikely that this will ever have any kind of performance impact on the program, but I still got curious whether this is a slow way of doing it.
Is there a risk that the construction of the string will involve a lot of reallocations? Would it be better (that is, faster) to use seekg()
/tellg()
to calculate the size of the file and reserve()
that much space in the string before doing the reading?