Skip to content

Commit 47dc554

Browse files
committed
ProgramMemory: avoid unnecessary copy in erase_if()
1 parent 1b807e1 commit 47dc554

1 file changed

Lines changed: 27 additions & 3 deletions

File tree

lib/programmemory.cpp

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,10 +173,34 @@ void ProgramMemory::erase_if(const std::function<bool(const ExprIdToken&)>& pred
173173
if (mValues->empty())
174174
return;
175175

176-
// TODO: how to delay until we actuallly modify?
177-
copyOnWrite();
176+
auto it = std::find_if(mValues->cbegin(), mValues->cend(), [&pred](const std::pair<const ExprIdToken, ValueFlow::Value>& entry) {
177+
return pred(entry.first);
178+
});
179+
if (it == mValues->cend())
180+
return;
181+
182+
// remove the (first) matching entry
183+
if (mValues.use_count() == 1)
184+
{
185+
it = mValues->erase(it);
186+
}
187+
else
188+
{
189+
const auto& exprIdTok = it->first;
190+
191+
copyOnWrite();
192+
193+
it = mValues->cbegin();
194+
for (; it != mValues->cend(); ++it) {
195+
if (it->first == exprIdTok) {
196+
it = mValues->erase(it);
197+
break;
198+
}
199+
}
200+
}
178201

179-
for (auto it = mValues->begin(); it != mValues->end();) {
202+
// remove the remaining matches
203+
for (; it != mValues->cend();) {
180204
if (pred(it->first))
181205
it = mValues->erase(it);
182206
else

0 commit comments

Comments
 (0)