Optimization of a C++ code (that uses UnorderedMap and Vector) -
i trying optimize part of c++ code taking long time (the following part of code takes 19 seconds x amount of data, , trying finish whole process in less 5 seconds same amount of data - based on benchmarks have). have function "add" have written , copied code here. try explain as possible think needed understand code. please let me know if have missed something.
the following function add called x times x amount of data entries.
void hashtable::add(pointobject vector) // pointobject user-defined object { int combinedhash = hash(vector); // function "hash" takes less 1 second x amount of data // hashtablemap unordered_map<int, std::vector<pointobject>> if (hashtablemap.count(combinedhash) == 0) { // if hashmap not contain combinedhash key, // add key , new vector std::vector<pointobject> pointvectorlist; pointvectorlist.push_back(vector); hashtablemap.insert(std::make_pair(combinedhash, pointvectorlist)); } else { // otherwise find key , corresponding vector of pointobjects , add current pointobject existing vector auto = hashtablemap.find(combinedhash); if (it != hashtablemap.end()) { std::vector<pointobject> pointvectorlist = it->second; pointvectorlist.push_back(vector); it->second = pointvectorlist; } } }
you doing lot of useless operations... if understand correctly, simplified form simply:
void hashtable::add(const pointobject& vector) { hashtablemap[hash(vector)].push_back(vector); }
this works because
- a map when accessed using
operator[]
create default-initialized value if it's not present in map - the value (an
std::vector
) returned reference can directlypush_back
incoming point it.std::vector
either newly inserted 1 or existing 1 if key in map.
note that, depending on size of pointobject
, other factors, possibly more efficient pass vector
value instead of const pointobject&
. kind of micro optimization requires profiling performed sensibly.
Comments
Post a Comment