Re: Techniques to avoid minimal scope inefficiency with complex
objects in loops in C++?
On Wednesday, June 6, 2012 8:07:00 PM UTC-4, Martin B. wrote:
On 06.06.2012 02:32, Ike Naar wrote:
Have you measured both variants? Which one was more efficient?
[D] is more efficient. It will re-use the buffer from string s a number
of times (except for the pathological case where the string lengths
increase strictly in steps larger than the allocation granularity of
string).
[C] will - must - delete the buffer of the s object each loop step and
do a fresh allocation.
cheers,
Martin
I use static locals in some places to help with this:
void
cmwAmbassador::mediateResponse (transactions_t::iterator itr)
{
bool safe_sending = true;
try {
localsendbuf.sock_ = itr->sock;
bool reqResult;
remoteMessages.Receive(cmwBuf, reqResult);
if (reqResult) {
setDirectory(itr->path.c_str());
static ::std::vector<File> outputFiles;
outputFiles.clear();
remoteMessages.Receive(cmwBuf, outputFiles);
save_lastruntime(itr->filename, itr->time_in_seconds);
safe_sending = false;
localMessages.Marshal(localsendbuf, true);
} else {
static ::std::string errorMsg;
errorMsg.clear();
remoteMessages.Receive(cmwBuf, errorMsg);
safe_sending = false;
localMessages.Marshal(localsendbuf, false, errorMsg);
}
localsendbuf.Flush();
} catch(::std::exception const& ex) {
#ifdef SYSLOG_AVAILABLE
syslog(LOG_ERR, "mediateResponse: %s", ex.what());
#endif
if (safe_sending) {
localMessages.Marshal(localsendbuf, false, ex.what());
localsendbuf.Flush();
}
}
}
(That function is part of this file --
http://webEbenezer.net/misc/cmwAmbassador.cc
and that file is part of this archive --
http://webEbenezer.net/misc/direct.tar.bz2
..)
That keeps the scope small and avoids the heap.
Usually someone will point out that statics don't
play well with multithreading. The cmwAmbassador is
currently single-threaded. G-d willing, in the
future we'll make it multi-threaded. The design of
the multi-threaded version of the program will be
such that a specific thread is responsible for calling
mediateResponse. So the statics will pose no more
problem then than they do today.
Brian Wood
Ebenezer Enterprises
http://webEbenezer.net
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]