Re: Fastest way to clone a hash_map
On Apr 29, 5:33 pm, devdude <rottygu...@yahoo.com> wrote:
I have the need to take a snapshot of a hash_map during
execution (actually transform it to a vector). This map is a
shared resource and therefore must be locked prior to any
read/write operations thus I need to minimize the amount of
time the map resource is locked.
The map is defined as type <string,
boost::shared_ptr<myobject>>. My algorithm is as such:
void SnapShotToVector( vector< pair< string,
boost::shared_ptr<myobject> >& vec )
{
lockResource(this->map);
vec.resize( map.size() );
copy(this->map.begin(), this->map.end(),list.begin());
unlockResource(this->map);
}
(Just a nit, but you really should use some sort of scoped lock
here. Both the resize and the copy can throw an exception,
leaving your resource forever locked.)
For about 3M elements w/in the map, I'm noticing that the
resize op takes about 150ms and the copy takes ~850ms. Is
there any way to do better? I suppose the total time doesn' t
matter as it's the time the resource is actually locked is the
primary concern.
There are really only two solutions: what you've done, and:
vec.reserve( map.size() ) ;
std::copy( map.begin(), map.end(),
std::back_inserter( vec ) );
Which one will be faster will depend on the implementation of
std::vector and std::string, so you'll have to measure. But
you're not going to get any order of magnitude gains.
You might also gain a little by resizing once before locking
(with perhaps a fudge factor, to allow for the map growing while
you're resizing):
size_t trialSize ;
lockResource( map ) ;
trialSize = 1.2 * map.size() ) ;
unlockResource( map ) ;
vec.resize( trialSize ) ;
lockResource( map ) ;
vec.resize( map.size() ) ;
copy( map.begin(), map.end(), vec.begin() ) ;
unlockResource( map ) ;
The resize in the locked zone should only change the size a
little, and hopefully will not increase it, so you'll only call
a few destructors.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34