Re: Efficient use of C++ Strings: Request for Comments
In article <1170582172.653485.135570@k78g2000cwa.googlegroups.com>,
"Ion Gazta?aga" <igaztanaga@gmail.com> wrote:
Nevin :-] Liber wrote> Talking about premature optimization, I would say that returning
strings by value, specially in the standard library where the size of
the string is unknown, is premature pessimization.
I disagree. It emphasizes correctness. Value semantics are far easier
to get right than reference semantics, because the latter always has to
worry about aliasing.
Take a simple function to concatenate two strings:
std::string concatenate(std::string lhs, std::string const& rhs)
{ return lhs += rhs; }
Maybe not the most efficient version in the world, but I'm pretty sure
it is correct.
I'll let you try doing it with (non-const) reference semantics:
void concatenate(std::string const& lhs, std::string const& rhs,
std::string& result);
It should do no copying of std::strings and only one resize() of result.
It needs to be correct whether or not lhs, rhs and result are the same
string, different strings, or any combination thereof.
Unless it is a measurable bottleneck, I'll take the simplicity of mine
over the complexity of yours.
I tend to focus on correctness as long as the efficiency is "good
enough" (and "good enough" is different for different applications).
That depends on what's "good enough". Maybe the problem is that
nowadays "good enough" sets the bar too low.
It doesn't set the bar at all. It's just we have to optimize for
different things at different times: programmer time, run time
efficiency, space efficiency, predictability, responsiveness, etc.
You just need to see how
some applications are getting more and more inefficient and use so
much resources to do exactly the same thing another application did
with 3 times less resources.
isn't it. It is about knowing when it is worth taking the risk and
spending the time to write, inspect and test more complicated code. All
the best software engineers that I know take their professional pride in
making that decision correctly as well as when they reduce the bloat.
It is a waste of time to optimize away a plentiful resource. The trick
is in identifying which resources are scarce (and when they are scarce).
--
Nevin ":-)" Liber <mailto:nevin@eviloverlord.com> 773 961-1620
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]