Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!gegeweb.org!de-l.enfer-du-nord.net!feeder2.enfer-du-nord.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Ian Collins Newsgroups: comp.lang.c++ Subject: Re: STL map insert Options Date: Thu, 14 Jul 2011 16:50:47 +1200 Lines: 52 Message-ID: <987av2F78bU2@mid.individual.net> References: <526778d1-e768-4ee3-b42e-f8cc9444fab9@t8g2000prm.googlegroups.com> <983r38FglrU1@mid.individual.net> <986bn2FglrU4@mid.individual.net> <4e1e6bae$0$3476$c3e8da3$12bcf670@news.astraweb.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net y2wtB9CwGKnUK1Zuxi3bBQdrSVLNEAETDVSrzYo4m3GDhCti8n Cancel-Lock: sha1:qzzZDd2ARg5QCCxGvMfXhWveNmQ= User-Agent: Mozilla/5.0 (X11; U; SunOS i86pc; en-US; rv:1.9.2.9) Gecko/20101021 Lightning/1.0b2 Thunderbird/3.1.4 In-Reply-To: <4e1e6bae$0$3476$c3e8da3$12bcf670@news.astraweb.com> Xref: x330-a1.tempe.blueboxinc.net comp.lang.c++:7789 On 07/14/11 04:07 PM, Pavel wrote: > Ian Collins wrote: >> On 07/14/11 02:31 AM, Stephen Howe wrote: >>>> I'd be very surprised if all three didn't compile down to the same >>>> assembly code. It certainly does with the two compilers I tried. >>>> >>>> Ian Collins >>> >>> I have just rechecked with Visual Studio 2008, 8 years later and I get >>> the same results. >>> And that is with full optimisations switched on. >>> It is easy to see why as make_pair()/pair() are creating an actual >>> object to insert, value_type does not. So that is an extra round of >>> copy constructors/destructors. >>> You might be using ints and the compilers you use might optimise out >>> extra assignments. >>> >>> With the code referenced in the link, I get (and it is not too hard to >>> work out what work map actually does). >> >> If you change the code to use the same type as the map::value_type, all things >> are equal. For example: >> >> m.insert(pair(t2, tv)); > const is the key here; otherwise there will be the second copy; same with make_pair. > > e.g. reasonably looking > > > std::map m; > m.insert(std::make_pair(1,2)); > > will lead to 2 copies: first std::pair(), then std::pair int>(std::pair); > > That's why for performance reasons, value_type or a typedef is a better option. > For same reason make_pair is one of the "evil" functions that I never use: it's > too easy to introduce an accidental extra copy. Indeed. A little helper like template std::pair map_pair( const Key& key, Value& value ) { return std::pair(key, value); } can come in handy. -- Ian Collins