Avoid double traversal of maps

The typical find/if-not-exists-insert pattern can be achieved with 1
lookup instead of 2 using emplace with a sentinel value. Also maps value
initialize their values when inserted with the [] operator, this is
defined and so there is no need to explicitly insert zeroes for integer
values.
This commit is contained in:
Geza Lore
2023-10-28 13:41:43 +01:00
parent 30318a6654
commit d60f180f43
25 changed files with 240 additions and 311 deletions
+5 -8
View File
@@ -991,10 +991,8 @@ public:
string protectIf(const string& old, bool doIt) VL_MT_SAFE_EXCLUDES(m_mutex) {
if (!v3Global.opt.protectIds() || old.empty() || !doIt) return old;
const V3LockGuard lock{m_mutex};
const auto it = m_nameMap.find(old);
if (it != m_nameMap.end()) {
return it->second;
} else {
const auto pair = m_nameMap.emplace(old, "");
if (pair.second) {
string out;
if (v3Global.opt.debugProtect()) {
// This lets us see the symbol being protected to debug cases
@@ -1009,16 +1007,15 @@ public:
// See if we can shrink the digest symbol to something smaller
for (size_t len = 6; len < out.size() - 3; len += 3) {
const string tryout = out.substr(0, len);
if (m_newIdSet.find(tryout) == m_newIdSet.end()) {
if (m_newIdSet.insert(tryout).second) {
out = tryout;
break;
}
}
}
m_nameMap.emplace(old, out);
m_newIdSet.insert(out);
return out;
pair.first->second = out;
}
return pair.first->second;
}
string protectWordsIf(const string& old, bool doIt) VL_MT_SAFE {
// Split at " " (for traces), "." (for scopes), "->", "(", "&", ")" (for self pointers)