I would like to read an file into a string. I am looking for different ways for how to do it efficiently.
Using a fixed size *char buffer
I
it only happens in the memory, not from the disk, so it is almost unnoticable
That is indeed correct. Still, a solution that doesn’t do that may be faster.
Why are those iterators so slow?
The code is slow not because of the iterators but because the string doesn’t know how much memory to allocate: the istreambuf_iterators can only be traversed once so the string is essentially forced to perform repeated concatenations with resulting memory reallocations, which are very slow.
My favourite one-liner, from another answer is streaming directly from the underlying buffer:
string str(static_cast(stringstream() << in.rdbuf()).str());
On recent platforms this will indeed pre-allocate the buffer. It will however still result in a redundant copy (from the stringstream to the final string).