Any possiblity to avoid costy construction of temporary?

  • Permalink
  • submit to reddit
  • Email
  • Follow


I have a hash class which is expensive to create but are often used
for comparsion. Consider the following code:

[code]
void SomeFunc( Hash someHash )
{
     if( Hash("SomeLengthyString") == someHash )
     {
          ...
     }
}
[/code]

Hash("SomeLengthyString") is expensive to construct and will stay
constant for all calls to SomeFunc. I understand that the compiler
isn't allowed to cache Hash("SomeLengthyString") through calls since
it's a performance / memory trade off, and from the compilers pov the
constructor of Hash might have additional dependencies. I would get
the expected behaviour if I would make Hash("SomeLengthyString")
static, which led me to the following code, which even compiles under
MSVC2005:

[code]
void SomeFunc( Hash someHash )
{
     if( static Hash("SomeLengthyString") == someHash )
     {
          ...
     }
}
[/code]

However the constructor of Hash is still called once for every
comparsion.

Regards,
Sebastian Karlsson

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Sebastian 3/23/2008 7:42:58 PM

See related articles to this posting


Sebastian Karlsson wrote:

> Hash("SomeLengthyString") is expensive to construct and will stay
> constant for all calls to SomeFunc. I understand that the compiler
> isn't allowed to cache Hash("SomeLengthyString") through calls since
> it's a performance / memory trade off, and from the compilers pov the
> constructor of Hash might have additional dependencies. I would get
> the expected behaviour if I would make Hash("SomeLengthyString")
> static, which led me to the following code, which even compiles under
> MSVC2005:
> 
> [code]
> void SomeFunc( Hash someHash )
> {
>      if( static Hash("SomeLengthyString") == someHash )
>      {
>           ...
>      }
> }
> [/code]
> 
> However the constructor of Hash is still called once for every
> comparsion.
> 


g++ does not accept that construct at all. Complaining:

<snip>
error: expected primary-expression before �static�
</snip>

Seems like you're constructing a static temporary variable,
since there is no object name only the constructor Hash(...).

Anyway. If I do:

<snip>
....
static Hash h("SomeLengthyString");
if( h == someHash) {
....
}
</snip>

it behaves like expected. Sometimes dense expressions
like declaration and comparison in one line is evil.
Although I like it too :-).

Hope that helps.

O.



-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Oncaphillis 3/23/2008 11:22:39 PM

In article
<f3e582e0-25bf-4b2c-b507-159559353f44@e23g2000prf.googlegroups.com>,
Sebastian Karlsson <Sebastian.Karlsson@mmorpgs.org> wrote:

> I have a hash class which is expensive to create but are often used
> for comparsion. Consider the following code:
> 
> [code]
> void SomeFunc( Hash someHash )
> {
>      if( Hash("SomeLengthyString") == someHash )
>      {
>           ...
>      }
> }
> [/code]
> 
> [code]
> void SomeFunc( Hash someHash )
> {
       static Hash  const_hash("SomeLengthyString");
       if( const_hash == someHash)
       ...
}
> 
> However the constructor of Hash is still called once for every
> comparsion.
>

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Carl 3/23/2008 11:23:15 PM
comp.lang.c++.moderated 10647 articles. 9 followers. Post

2 Replies
223 Views

Similar Articles

[PageSpeed] 12


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

avoiding temporaries
Dear group, I would like to ask if the following code is legal C++ and whether NRVO optimization is applicable at operator=(). Consider the following example: #include <new> class Vector { public: Vector() { } Vector( const Vector & v ) { for( int i = 0; i != 20; i++ ) { data[ i ] = v.data[ i ]; } } Vector( const Vector & u, const Vector & v ) // Addition { for( int i = 0; i != 20; i++ ) { data[ i ] = u.data[ i ] + v.data[ i ]; } ...

Copy Construction and temporaries
I came across a document outlining the "Programming Research Group"'s "High integrity C++ Coding Standard Manual": http://www.codingstandard.com/HICPPCM/index.html and an example for a particular rule of theirs gave me pause: http://www.codingstandard.com/HICPPCM/Rule_3.1.2.html In it, they claim that using assignment syntax to construct an object is not the same as using constructor syntax. The example they give is: string a1 = "Hello"; string b1 = string("Hello"); string c1("Hello"); and they go on to claim that in the construction ...

Possible to avoid RTTI?
Given this situation: class Base { public: virtual ~Base(); virtual bool equals(Base const&) const = 0; }; Base::~Base() {} inline bool operator==(const Base& a, const Base& b) { return a.equals(b); } class Derived : public Base { public: bool equals(const Base& b) const { if (typeid(*this) == typeid(b)) { return data_ == b.data_; } return false; } private: int data_; }; // in use Base& a(getA()); Base& b(getB()); return a == b; Is there any way I can do this without RTTI? I was thinking of somet...

temporary require ,is it possible?
I have a idea,it is "temporary require" [code] module Find # my define end tmp_require("find"){ #do something with "Find.find" method,temporary!! } puts Find # my define,no "Find.find" method [/code] Is it possible? -- Posted via http://www.ruby-forum.com/. On Thu, May 24, 2007 at 06:03:22PM +0900, Gpy Good wrote: > I have a idea,it is "temporary require" > [code] > module Find > # my define > end > > tmp_require("find"){ > #do something with "Find.find" method,temporary!! > } > >...

Avoid HTTPS when possible?
After the recent CA desasters, I wonder if one should avoid HTTPS whenever possible, in order not to create a false sense of security. I registered a .NAME domain some time ago and put some contact information there, including OpenPGP key and e-mail addresses. I was thinking of putting the URL with 'https' prefix on my visiting cards. But then I would like to give visitors the opportunity to check whether the site they are connected to is in fact run by the person who gave them the visiting card. So I would put the SSL fingerprint of my webserver on the visiting card, in order...

avoiding temporary and filesort
Hi, I have the following query: select uid,count(uid) from A group by uid; The explain plain informs me that it is using temporary and filesort. Is there a way to optimize this query without having to use file sort or temporary? Is it possible to use a view with two column, uid and count. Every time the uid column is updated, the count coulumn gets incremented? Thanks. On 8 Dec, 16:38, tekion <tek...@gmail.com> wrote: > Hi, > I have the following query: > > select uid,count(uid) from A group by uid; > > The explain plain informs me that it is using temporary and &...

How to avoid a temporary table
Hello, Often I have seen opinions in this group that temporary tables are not necessary and can always be avoided. I don't like (the oracle way of) temporary tables and would like to avoid them, if possible. However I feel that often they are unavoidable in order to "modularize" SQL, i.e. avoid multiple occurrance of similar pieces of SQL. I know that you can always rewrite a temporary table as a subquery. Often however, you end up using multiple subqueries that are very similar, i.e. duplication of "code", that you avoid in "normal" programming languages b...

Is it possible to avoid the save a PDF?
Hi, excuse my english (I'm Italian) I have created a website and there's a page in which I would like to show a pdf file but I would like to protect from saving and copying. Is it possible? If yes, how? Thank you "bettina68" <bettina68@yahoo.it>, In a message on Sat, 13 May 2006 13:12:57 +0200, wrote : "> Hi, excuse my english (I'm Italian) "> "> I have created a website and there's a page in which I would like to show a "> pdf file but I would like to protect from saving and copying. "> Is it possible? If ye...

Is it possible to dynamically construct arguments to With[]?
I've been trying to construct a list of local variables for the With construct dynamically, with no avail. I tried various combinations of Unevaluated, Hold, and even ToBoxes/MakeExpression. I've read that With[] evaluates its initialization lists in a non-standard way (cf http://library.wolfram.com/conferences/devconf99/villegas/UnevaluatedExpressions/Links/index_lnk_7.html) -- is this the problem?.. Is it possible to achieve something like the code below? (* this doesn't wok *) Clear[aa, a]; aa = List[Unevaluated[a = 3]]; With[aa, a*100] // Print; (* want 300 *) ...

Is it possible to have temporary memory files?
Is it possible to create a temporary file in a shell script that lasts for the duration of the process but is purely local to the invoked shell such that it is readable and recognised within the shell but not visible by any other process and it disappears once the shell ends? RolandRB wrote: > Is it possible to create a temporary file in a shell script that lasts > for the duration of the process but is purely local to the invoked > shell such that it is readable and recognised within the shell but not > visible by any other process and it disappears once the shell ends? > H...

possible to avoid a shadow merge?
I have a new ALPHA as a satellite in my cluster. The idea is to boot it up only when CSWB is being used, as the other systems don't have the resources. (The machine is too power-hungry to leave on all the time.) I have SYSUAF etc on a non--system-disk shadow set. As a result, this disk can't be dismounted before shutting down the satellite (at least not easily), due to open files. Under what conditions will shutting down and rebooting the satellite cause a merge on this disk (or any other disks it can't dismount due to open files (assuming the applications with the open f...

Is it possible to eliminate the temporary variable
Hi all, I use the following script to read a file and create a 2D array. What bothers me is that I have to use a temporary variable. I wonder if there is a better way to read a file and create a 2D array. Thanks, Li ################## # create a 2D array def file_process @data=[ ] # read in the file line by line File.open(@file) do |a_file| temp=[] a_file.each_line do|a_line| a_line.chomp!# remove \n temp=a_line.split(/\t/) # tab is the separator @data << temp temp=[] end end end -- Posted via http://www.ruby-forum.com/. Is this work? def...

Avoid accidentally creating a temporary
Dear Experts, Say I have this: struct scoped_foo { scoped_foo(int n) { enable_foo(n); } ~scoped_foo() { disable_foo(); } }; and I use it like this: { scoped_foo(3); blah(); // foo is enabled here } // foo is disabled here ....except that doesn't work, because I should have written { scoped_foo ANY_NAME_HERE(3); .... I've now made this mistake a few times, and it's annoying. So, my question: is there anything that I can do in my declaration of scoped_foo so that trying to use it in this wrong way, i.e. to create a temporary rather than an object with scope up to...

Avoiding copy construction when growing a vector
Hi, When growing a std::vector, I had assumed (incorrectly) that std::swap was used to move the elements without needing to create a copy of each element. It seems that I was quite wrong on this point. Is there any way to grow a vector without calling the copy constructor for each element? I realize that C++0x will have std::move, but I need a solution that is standard and works now. Thanks, Shaun -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] On 16/10/2010 01:22, ShaunJ wrote: >...

Is it possible to avoid loading the script for each request
I do not know PHP, consider to write a CGI with this technology and have the following question. Is it possible to invoke a PHP script and let it endlessly wait for requests from a website (a Java applet in my case) and serve the requests when they arrive? I want to avoid loading the script for each request. In other words, can it function, in this sense, like a Java servlet? On Jun 1, 3:00 am, DavidNorep <avdavid.nore...@gmail.com> wrote: > I do not know PHP, consider to write a CGI with this technology and > have the following question. > > Is it possible to invoke a PH...

cast constant vs. construct temporary
Is there a difference between the expressions "size_t(-1)" and "(size_t)-1"? In context, say: void Some_Function(size_t); Some_Function(size_t(-1)); //pass a flag value to Some_Function * Adam: > Is there a difference between the expressions "size_t(-1)" and > "(size_t)-1"? The former is defined to mean the same as the latter, as an isolated expression. -- A: Because it messes up the order in which people normally read text. Q: Why is it such a bad thing? A: Top-posting. Q: What is the most annoying thing on usenet and in e-mail? Alf P. St...

avoiding EVAL for the construction of functions at runtime
Hi, I am trying to incorporate Dr M. Balda's LMFnlsq implementation for the the Levenberg-Maquardt algoritm (http://www.mathworks.com/matlabcentral/fileexchange/17534) into my analysis package. This function can be used for fitting models into experimetal data, and in many cases it performs better then the built-in fit function. However, while the built-in fit function requires only an expression for the fit function, LMFnlsq requires a function handle or a function M-file name that evaluates m-vector of equation residuals. That becomes a problem when i want to offer the user an optio...

optimization, avoid loop possible? ..intersect?
I am writing a simple function that takes an input, for example % input.. a=[4 3.5]; % and the function is.. function omega=give_value(a) x=[1 2 3.5 4]; y=[2 4 2 1]; for n=1:length(a) out(n)=y(x==a(n)); end This will be called many times, so I would like to avoid the loop, however intersect does not work as: [c, ix, ia]=intersect(x,a) omega=y(ix) gives an omega that is not right, since intersect sorts its output, and i want to keep the order with respect to a. Any ideas? / Matias "matias nordin" <matias.nordin@gmail.com> wrote in message <guutrb$br3$1@f...

Is it possible to avoid the "for" cycle here?
Dear all, I am aware that we should use as little as possible "for" cycle . But in the following case is it still possible to write it in a compact form avoiding the cycle? If yes how? for i =1:cells BETAprint(i) = BETAs(i,Kact(i,k),J-10000,k) end the problem here is that Kact is itself a function of "i" thanks A. On 10/9/2012 5:15 PM, Alberto wrote: > Dear all, > I am aware that we should use as little as possible "for" cycle . But in > the following case is it still possible to write it in a compact form > avoiding the cycle? If ye...

Is it possible to create index for temporary table
Hi Friends, Is it possible to create index for temporary table? Is so tell me how to acheive that.. Thanks, Thiru WantedToBeDBA@gmail.com WantedToBeDBA wrote: > Hi Friends, > Is it possible to create index for temporary table? Is so tell me > how to acheive that.. > Thanks, > Thiru > WantedToBeDBA@gmail.com CREATE INDEX... I think it was introduced in DB2 V8.1 for LUW (or was it V7.2...??) Thanks Friends.. Its possible to create index for declared temporary tables but not for created temporary tables. I have completed my task successfully.. ...

Is it possible to specify the size of list at construction?
I cannot figure out how to specify a list of a particular size. For example, I want to construct a list of size 10, how do I do this? __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail ...

Temporary object construction or pointer to function declaration?
Hello, everybody, I've encountered strange compilers behavior (most likely "undefined behavior"), but I've spent an hour, trying to find out, appropriate C+ + standard paragraph and I was unsuccessful. I would be grateful if somebody suggested me the correct direction of investigation, and why Comeau compiler and GCC doesn't display even a warning for this: Let's we have trivial structure with default c'tor and copy c'tor: struct S { S(); S(const S&); } ; And want do declare variable "v" of type "S" with passing of temporary object &...

avoiding flash memory writes as much as possible
Hello- Im not sure if this is the group to ask so forgive me if so please point me to the right group. Im working on an embedded x86 board that has a 4G flash RAM and has a threshold of about 10k writes. Im writing software that, unless I have a better way to do it, writes a file to the flash every 5 seconds, 24 hrs a day. The file being written is then picked up by a second process and analyzed. So Im trying to avoid disk (flash memory) writes so I dont wear out the flash. Ive been looking into named pipes or IPC msg sending but I think that they too write to 'disk'. My last re...

Avoiding SMTP spoofing with Cisco PIX. It is possible ?
Hi, I am using a Trend Viruswall SMTP like a Mail gateway. It is behind cisco PIX using NAT and SMTP Fixup. I want to know I there is a way to avoid mail spoofing (Using a valid internal mail address to send mail to another valid internal mail from outside) ? Thanks "Javier" <jvillegas@elsitio.net> wrote in message news:pFy6d.115$424.40@fe33.usenetserver.com... > Hi, > > I am using a Trend Viruswall SMTP like a Mail gateway. It is behind > cisco PIX using NAT and SMTP Fixup. > > I want to know I there is a way to avoid mail spoofi...