Any possiblity to avoid costy construction of temporary?

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
Sebastian
3/23/2008 7:42:58 PM
comp.lang.c++.moderated 10708 articles. 0 followers. allnor (8507) is leader. Post Follow

2 Replies
266 Views

Similar Articles

[PageSpeed] 57
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
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
Carl
3/23/2008 11:23:15 PM
Reply:
Similar Artilces:

Is strong AI possible?
http://en.wikipedia.org/wiki/Computational_theory_of_mind The key question is: What would be the undetectable difference between an actual living mind and a perfect simulation of a living mind? The distinction between an actual living mind and a perfect simulation of an actual living mind might be divided by how one defines consciousness. If consciousness is defined as having a will of one's own, then the AI mind (with a sufficiently populated goal hierarchy) might be considered to be equivalent to a living mind. Although it may still be gears and pulleys on the inside, o...

Compiler Construction Seminar (Astoria OR, Sept 09)
On September 20-22 there's a Compiler Construction seminar in Astoria, Oregon. It will cover practical techniques in building a compiler, from lexing to code generation. http://www.astoriaseminar.com There will be 9 sessions: Introduction To Compilers Walter Bright (1.5 hrs) This introduces the process of how source code is transformed into an executable image. The roles of each of the tools involved - assembler, compiler, linker, librarian and debugger is explained. The compiler is then opened up and its various phases, subsystems and their interrelationships are introduced. Lexing ...

Possible problem with iterators in STL
Hi everyone I have a problem with Iterators and containers in STL that hopefully someone can help me with. This is what I try to do: I have an associative (map) container and I have a function where I with the help of iterators want to search through the container and remove a certain object in the container. Here is part of the code in that function: //Move from timers map container to stale list container Timers::iterator start(_timers.begin()); Timers::iterator last(_timers.end()); while (start != last) { if(compObj.Compare(start->second)) { _stale.p...

Avoiding "ORA-04091 table string.string is mutating"
Hi, maybe this is a faq but I didn't find any solution... I have a table like this one, which describes some time intervals in the form [startdate,enddate]. create table mytab ( startdate date not null, enddate date not null ) I don't want this table to contain overlapping intervals: it must be impossible to insert a record that overlaps with an already existing one or to update an existing record in order to make it overlap over onto another one. I had no problems in writing a before insert trigger that performs the required test, but I don't know how this check ...

is it possible?
The seller of the CD-ROM drive that I claimed was broken, because it did not work, although the drive sled was good, has claimed that the CD-ROM drive works. He did not have a 6360 to test. I have a Performa 6360 and the Apple 24X drive slid right into my Mac, the drive sled was good. I did not touch any of the jumpers or anything. I am wondering if any of you think its at all possible that something inside my Macintosh may be broken and the reason why I could not get the internal CD-ROM drive to work on my Mac? Or maybe perhaps the jumpers on the back of the drive were set for his ...

Feedback sought on tool to help users avoid bugs
Hi, We have been working on the Stabilizer, a tool to help users avoid bugs in GUI applications. We would like to see how well it works on as many Java GUI applications as possible, and so, we are asking for your feedback on the tool. To give us feedback, all you have to do is this: (1) pick a Java GUI application (2) pick a feature in that application (it is ok for the feature not to be buggy for the purposes of this test) (3) try to get the Stabilizer to report bug warnings on that feature but not on other features The feature of interest may or may not involve context. For example, sel...

Treo 650 ppp connection in the US . Possible ?
Hi, I know this works in the Europe via GSM data connection - I do this from my Tungsten T. However I'm trying to help a friend in the US configure his Treo 650 to access his corporate email via IMAP. He needs to dial into the companies intranet as the IMAP4 servers are inside the firewall. Q: He seems to be having problems, and I have never actually tried this config outside Europe. Is it possible to make a ppp connection from a Treo 650 in the US ? I don't mean a GPRS connection but a good old 14.4K dialup data connection ? Maybe he needs to ask his providor to enable...

Constructing IN List values
Hi, I wanted to give user an option to send a group of values so I could use that list in my in list. What I want here is I want the user do not bother about putting the quotes around each value. I wanted to handle that in my program whether user passes just space sepearted list alfred janet or delimeter seperated list alfred, janet etc. Here is my test macro. TIA, Garland options mlogic mprint symbolgen; %macro intest(inlist=); data test; set sashelp.class; where upcase(name) in (%upcase(&inlist)); run; %mend intest; %intest(inlist=%str('ALfred','janet')); I a...

Why is this not possible?
#!/bin/sh # this doesn't work in bash: # # usage: $1 is body of function, use inline # if it worked it would make it possible to simulate an anonymous function inline function lambda { name=tmp$(perl -e "print rand()*(2**50);") # make up unique function name $("function $name { $1 }") echo $name } # this works # shell can do callbacks, but unfortunately no anonymous functions # usage: function funa { ... }; function funb { ... }; percent funa funb function percent { fun1=$1 fun2=$2 echo $(echo "scale=2;"$($fun1)" / "$($fun2)" ...

Is it possible? #2
It is really a matter of disappointment that i'm not being able to create an executable Matlab file... Is it possible that i could run an m.file in a machine where Matlab is not installed? if possible then help me immediately! i must be greatful to you! Hi, This is possible, you need the toolbox "MATLAB Compiler" Then see help about the function "mcc" that will help you doing an executable file. Once your exe file built, you must First install a package on the machine that weit about 80Mo... regards, chris "Tapon Paul" <hemt_82@yaho...

its possible this?
If I have a graph and i put: ginput I take a point of the graph. It is possible to print the points while the user is above those points with this command, but without clicking, so the user will know exactly where do he wants to click and can do it??? THANKS Irinic wrote: > > > If I have a graph and i put: ginput > I take a point of the graph. > It is possible to print the points while the user is above those > points with this command, but without clicking, so the user will > know exactly where do he wants to click and can do it??? > > THANKS > u can use the &...

How to Create Local Temporary Table
Hi, I just migrate from SQL Server to Oracle. I usually use local temporary table in my SQL Server queries (sign with '#'). Now, could I create the local temporary table in Oracle too? Please help me, some example would be appreciated 'cause it will help me to understand. Thanks, Resant In Oracle A temporary table structure is visible to all session. Data is visible only to that particular session. you can have it either session specific or transaction specific. SQL> CREATE GLOBAL TEMPORARY TABLE mytemp (a number, b number) on commit delete rows; 2 Table created. SQL> ...

Rotating label text in A97? Is it possible?
I see in A97 HELP that rotating text in charts is possible. What about labels on forms and reports? See if Stephen Lebans's solution will help. http://www.lebans.com/xrotatetext.htm -- Wayne Morgan MS Access MVP "MLH" <CRCI@NorthState.net> wrote in message news:en71j1lqn0eid9fn8gb0le9f89leg2dsbj@4ax.com... >I see in A97 HELP that rotating text in charts > is possible. What about labels on forms and > reports? ...

Possible Lavasoft Ad-Aware false positive?
Hi everyone, Since yesterday, a scan using Ad-Aware warns me of a SpywareNo infection. Nevertheless, other antispyware programs such as microsoft antispyware, spybot s&d and ewido dont pick up any traces of this infection. Also, searching the web and looking at the possible symptoms of that infection, there are none of those mentioned in my laptop. No process spywareno.exe, no similar files, no pop ups. This is what the adaware scan gives: SPYWARENO =BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB= =BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB=BB obj[0]=3DRegk...

How to avoid no value defined value list say by displaying a custom message?
Hi ; I would appreciate to get me help in solving this question : How to avoid the message "no value defined" in value list once the releashinship does not support importing the value from another file . I want to replace this system generated message by say displaying a custom message! Thanks in advance Mushabab Al-Murayeh, MD ...

Possible to synchronise changed message headers?
Is this possible? * User synchronises their emails * Server changes message headers, eg. subject * Server pushes changes to connected email client (or updates on next resynchronisation) Obviously this change may affect message sorting, mail filters, etc., which would also need to be updated. Cheers, Jon Jonathan Melhuish wrote: > Is this possible? > > * User synchronises their emails > * Server changes message headers, eg. subject > * Server pushes changes to connected email client (or updates on next > resynchronisation) RFC3501 doesn't seem too friendly...

What is the smallest physically-possible voltage that can be detected or processed given the state of today's technology?
Hi: What is the smallest physically-possible voltage that can be detected or processed given the state of today's technology? Thanks On Mon, 1 Jun 2009 17:15:19 -0700 (PDT), GreenXenon <glucegen1x@gmail.com> wrote: >Hi: > >What is the smallest physically-possible voltage that can be detected >or processed given the state of today's technology? > > >Thanks You can buy nanovoltmeters that will resolve a couple of hundred picovolts, if you're careful. Superconductive SQUID detectors can measure a picovolt. Single-electron transistors can sense, well,...

Possibly off topic, possibly not
Is there a good tutorial on programming with ODBC/wxODBC? I'm fairly familiar with SQL and wxWindows, but I can't find any ODBC programming references out there, and the wxODBC (wxDb, wxDbTable and friends) topic in the documentation doesn't quite tell me how to do the programming. The project is basicly this: C++ program (written in wxWindows) talks to MySQL database. The program is going to be hosted on Win32 systems, while the MySQL database will be on Slackware Linux 9.1. I'll be using the latest wxWindows library. Compilers, if it's needed, are Visua...

Generating list of possible configurations
Hello pythonistas. I'm a newbie to pretty much both programming and Python. I have a task that involves writing a test script for every possible combination of preference settings for a software I'm testing. I figured that this was something that a script could probably do pretty easily, given all the various possibilites. I started creating a dictionary of all the settings, where each key has a value that is a list of the possible values for that setting. Most of the settings are simple booleans (setting is on or off), some of them are drop-downs with several values. For example: s...

Possible VISA-conflict between Agilent and NI-VISA?
We are making a program i labVIEW, using an oscilloscope (Tektronix TDS 2014), a signal generator (Agilent HP33120A) and a USB/GPIB-interface (Agilent 82357). When we use the Agilent VISA as primary VISA, the oscilloscope works just fine, but the signal generator won't work - neither connected with RS-232 nor with USB/GPIB. We usually get an instrument spesific error (-108: bad parameter) after running "config waveform.vi". At first we used the NI-VISA as primary VISA and an old AT/GBIB-card (1990). This was working allright, but we would rather like to use the USB/GPIB, but we c...

A Brain Transfer? Is That Possible?
I have just bought a Dell laptop after a serious accident with some liquid left my HP Armada 700 effectively dead. In the past, I would've used a peer-to-peer network to transfer my old files from the HP to a new laptop but with the HP laptop brain dead that option isn't gonna work. The motherboard is dead but the hard drive is probably still functional; does anyone know if the HP's hard drive can be physically transferred over to the Dell either to be used by itself or as a second HD for the Dell? Ron In an earlier contribution to this discussion, Ron <ryon@dslnorthwest.net...

Is possible to create my own scrolling bars?
The Subject says its all. I would like do this by JavaScript. Normally vertical scroll bar is at right side of a box and horizontal scroll bar is at bottom of a box. I would like change that. Make vertical scroll bar at left side of a box and horizontal scroll bar at top of a box. Please point me some URL links how to do this. Thank Q! RC wrote: > The Subject says its all. > > I would like do this by JavaScript. > ... > Please point me some URL links how to do this. http://www.dhtmlgoodies.com/index.html?page=smallscripts Search for "Scrollable div" RC wrote: ...

browser cant resolve domain name but pinging possible via same.
Hi I have Fedora Core 6 installed on my machine. I connect to a 'DSL' modem via 'Realtek' Etheret card .I am able to ping domain names like google.com / yahoo.com But none of the installed browsers is able to resolve any domain name .I have kept the same settings of IPs as in the windows. Please help. Thanks. vc wrote: > Hi > > I have Fedora Core 6 installed on my machine. I connect to a 'DSL' > modem via 'Realtek' Etheret card .I am able to ping domain names like > google.com / yahoo.com > > But none of the installed browsers is able...

How is this possible?
My removeable zip drive is normally J:. Every so often out-of-the-blue it becomes D: in "My Computer" and that then causes problems because all the other drives move up a letter, Data that should go to a partition goes into the partition physically nearer C: Yet, Partition Magic continues to show D: as it normally is, the next partition on my HD up from C:. Previously Richard <rubbish@email.com> wrote: > My removeable zip drive is normally J:. Every so often out-of-the-blue it > becomes D: in "My Computer" and that then causes problems because &...

Need to use Oracle RowID through ODBC
Hi All, I am using Access as a quickie front-end to our Oracle databases. One of our procedures writes the Oracle RowID to a custom column called ROW_NUMBER. I'd like to use that number in my WHERE clause for a table, but since Access doesn't see "RowID" anywhere, Access's SQL treats it as a parameter and asks me to enter "rowid" in as I execute the SQL. Anyone know if it's possible to use the Oracle RowID from within Access? Thanks, Jon If you create a view, and then link to that view, then any query you build in access based on that linked view can...