Re: Newby C++ vs. C question
alexrixhardson@yahoo.com wrote:
Hi guys,
I am a newby in the C/C++ world, and I am beginning to work on a
rather simple TCP/IP proxy application which must be able to handle
large volume of data as quickly as possible.
Since this application has to process and distribute plain text around
the network, I am wondering if there are any peformance differences
between C++ std::string and C char[] in run time?
Which one would you suggest me to use for my particular task (TCP/IP
proxy which is distributing plain text around the nextwork that
is :-) )?
Thanks, Alex
p.s.: here're two examples that I found on the Internet for which I am
wondering if there are any performance differences between them:
==========================
C function returning a copy
==========================
char *fnConvert(int _ii)
{
char *str = malloc(10); /* Return 10 character string */
if(str == NULL)
fprintf(stderr,"Error: Memory allocation failed.\n");
sprintf(str, "%d", _ii);
return str;
}
==========================
C++ function returning a copy
==========================
string fnConvert(int _ii)
{
ostringstream ost;
ost << _ii;
return ost.str();
}
Obviously, the C++ version is simpler, because the implementation does
a lot of the work under the hood. As far as efficiency or speed or
anything else, as Victor says, you'd have to test.
Disregarding optimization, the C++ version would do seem a bit more
work, what with allocating in the first place, then copying the string
for return. However, the compiler might well do things more
efficiently, so there may be little difference, or the C++ version
might be better. No way to tell.
When working in C or C++ with plain arrays, you can often improve
efficiency by not doing dynamic allocations at all. It would depend on
the specific application, but for networking there's often one send
buffer declared at the start, and all new messages built in that.
In most modern systems, the hardware has gotten so good, and the
compilers so clever, that micro-optimization of the code isn't needed.
Do you really care if the program takes 600 milliseconds to execute,
rather than 200?
In general, you should work in the language and style that is most
comfortable and most clearly expresses what you want. If performance is
acceptable, then you're done. Otherwise, profile and correct
bottlenecks.
Brian