Skip to content

Commit 204ca67

Browse files
committed
Reduce cache lookups in CCoinsViewCache::FetchCoin
Enhanced efficiency and readability of CCoinsViewCache::FetchCoin by replacing separate find() and emplace() calls with a single try_emplace(), reducing map lookups and potential insertions.
1 parent 27a770b commit 204ca67

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

src/coins.cpp

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,19 +43,18 @@ size_t CCoinsViewCache::DynamicMemoryUsage() const {
4343
}
4444

4545
CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
46-
CCoinsMap::iterator it = cacheCoins.find(outpoint);
47-
if (it != cacheCoins.end())
48-
return it;
49-
Coin tmp;
50-
if (!base->GetCoin(outpoint, tmp))
51-
return cacheCoins.end();
52-
CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first;
53-
if (ret->second.coin.IsSpent()) {
54-
// The parent only has an empty entry for this outpoint; we can consider our
55-
// version as fresh.
56-
ret->second.AddFlags(CCoinsCacheEntry::FRESH, *ret, m_sentinel);
46+
const auto [ret, inserted] = cacheCoins.try_emplace(outpoint);
47+
if (inserted) {
48+
if (!base->GetCoin(outpoint, ret->second.coin)) {
49+
cacheCoins.erase(ret);
50+
return cacheCoins.end();
51+
}
52+
if (ret->second.coin.IsSpent()) {
53+
// The parent only has an empty entry for this outpoint; we can consider our version as fresh.
54+
ret->second.AddFlags(CCoinsCacheEntry::FRESH, *ret, m_sentinel);
55+
}
56+
cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
5757
}
58-
cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
5958
return ret;
6059
}
6160

0 commit comments

Comments
 (0)