Re: Efficient use of C++ Strings: Request for Comments
On Jan 31, 9:32 am, Scott McKellar <m...@swbell.net> wrote:
Having put up some web pages about how to use C++ strings
efficiently, I hereby invite my betters to rip them to shreds:
http://home.swbell.net/mck9/effstr/
[snip]
Let me first ask you if you have verified your recommendations. Some
of them are very dangerous and some are downright wrong.
As an example, let us take a look at recommendation 1: Allocate
strings statically, not on the stack. You suggest replacing
void prepend_hello( string & greeting )
{
string hello( "Hello, " );
hello += greeting;
greeting = hello;
}
with
void prepend_hello( string & greeting )
{
static string hello;
hello = "Hello, ";
hello += greeting;
greeting = hello;
}
on the grounds that constructing a string is expensive. The problem is
two-fold: first of all, creating an empty string is very cheap and
thus you would not save much by having it global. Secondly, in the
example with the static string, every entry to the function might very
well require an allocation and a deallocation of memory: in effect,
the statement hello = "Hello, " is the same as hello =
std::string("Hello, "), making it obvious that your effort is wasted.
But the worst part of your suggestion is that you suddenly has created
a program that is no longer thread-safe. If two threads should call
prepend_hello at (about) the same time, the program will likely crash.
Your fourth recommendation is to avoid returning strings. You
recommend
void get_version( string & s )
{
const char * p = getenv( "OEE_VERSION" );
s = p ? p : "1.0";
}
rather than
string get_version()
{
const char * p = getenv( "OEE_VERSION" );
return p ? p : "1.0";
}
and recommend we use the three-liner
static string version;
get_version( version );
cout << "Version " << version << endl;
instead of the more straight-forward one-liner:
cout << "Version " << get_version( ) << endl;
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]