On 20/02/07, Joseph Artsimovich <joseph@stripped> wrote:
> Actually, my code should be faster than yours.
> An extra call to std::stringbuf::str() in your code will likely be slower than
> constructing a temporary std::string from another string. On most platforms
> the former will allocate memory while the latter will use reference counting.
That depends.
I think GCC is the last major platform still using ref-counted
strings, and they plan to switch to the small string optimisation next
time there is an ABI-breaking (non-binary compatible) version. And
ref-counted strings in threaded systems can be slower than
non-ref-counted.
But I agree that repeated calls to stringbuf::Str shoudl be avoided.
Why not use the best of both worlds, take a const-reference to the
string returned by stringbuf::str and then you don't need to care how
your strings are implemented:
Query::preview_char()
{
std::string const& str(sbuffer_.str());
char* s = new char[str.size() + 1];
memcpy(s, str.c_str(), str.size() + 1);
}
(N.B. technically std::string::c_str might allocate memory, but I
don't know of any implementation that does in practice)
jon