ph*******@yahoo.com (Phlip) wrote:
Here's the question: What's the fastest, or smallest, or smarmiest
possible Standard Library implementation? Could something like
std::copy() apply?
Here is what should be the fastest approach:
std::string fileToString(std::string const& name) {
std::ifstream in(name.c_str());
return std::string(std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>());
}
Since this is a pretty specialized call and a few optimizations are
necessary for this to be fast, it is likely that the constructor of the
string internally actually does something like
std::copy(begin, end, std::back_inserter(*this));
.... and the actual optimizations are applied to 'std::copy()'. I'm, however,
not aware of any standard C++ library which currently optimizes stuff like
this to an extreme level: for this to be fast, it would be necessary to
'reserve()' memory before going ahead and actually reading the string. To
figure out the size, in turn, it would be necessary to have a difference
function which is specialized for 'std::istreambuf_iterator<>()' which
takes the underlying code conversion facet into account and which is indeed
used: 'std::istreambuf_iterator' is an input iterator and thus using
'std::distance()' would consume the sequence. On the other hand, it is
definitely doable. Of course, the copies are not necessarily that expensive
and it may be viable to dump the file blockwise into a string.
My guess is that the fastest approach to reading a file into a string using
current standard C++ library implementations involves using an
'std::ostringstream':
std::string fileToString(std::string const& name) {
std::ifstream in(name.c_str());
std::ostringstream out;
out << in.rdbuf();
return out.str();
}
Stream buffer operate block-oriented internally anyway while the iterator
approach requires that the "segmented sequence" optimization is implemented.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
Phaidros eaSE - Easy Software Engineering: <http://www.phaidros.com/>