From 7cb6bcfdf6c279c00863b4470f6d863aff602317 Mon Sep 17 00:00:00 2001 From: metab0t Date: Fri, 30 Aug 2024 12:40:27 +0800 Subject: [PATCH] Some micro optimization of hashmap to use lookup and insert/modify --- lib/core.cpp | 46 ++++++++++++++++++---------------------------- 1 file changed, 18 insertions(+), 28 deletions(-) diff --git a/lib/core.cpp b/lib/core.cpp index eeae479..c117182 100644 --- a/lib/core.cpp +++ b/lib/core.cpp @@ -329,14 +329,12 @@ void ExprBuilder::_add_quadratic_term(IndexT i, IndexT j, CoeffT coeff) { std::swap(i, j); } - auto it = quadratic_terms.find({i, j}); - if (it == quadratic_terms.end()) + VariablePair vp{i, j}; + auto ret = quadratic_terms.emplace(vp, coeff); + if (!ret.second) { - quadratic_terms.insert({{i, j}, coeff}); - } - else - { - it->second += coeff; + auto &iter = ret.first; + iter->second += coeff; } } void ExprBuilder::_set_quadratic_coef(IndexT i, IndexT j, CoeffT coeff) @@ -345,14 +343,12 @@ void ExprBuilder::_set_quadratic_coef(IndexT i, IndexT j, CoeffT coeff) { std::swap(i, j); } - auto it = quadratic_terms.find({i, j}); - if (it == quadratic_terms.end()) - { - quadratic_terms.insert({{i, j}, coeff}); - } - else + VariablePair vp{i, j}; + auto ret = quadratic_terms.emplace(vp, coeff); + if (!ret.second) { - it->second = coeff; + auto &iter = ret.first; + iter->second = coeff; } } void ExprBuilder::add_quadratic_term(const VariableIndex &i, const VariableIndex &j, CoeffT coeff) @@ -366,26 +362,20 @@ void ExprBuilder::set_quadratic_coef(const VariableIndex &i, const VariableIndex void ExprBuilder::_add_affine_term(IndexT i, CoeffT coeff) { - auto it = affine_terms.find(i); - if (it == affine_terms.end()) + auto ret = affine_terms.emplace(i, coeff); + if (!ret.second) { - affine_terms.insert({i, coeff}); - } - else - { - it->second += coeff; + auto &iter = ret.first; + iter->second += coeff; } } void ExprBuilder::_set_affine_coef(IndexT i, CoeffT coeff) { - auto it = affine_terms.find(i); - if (it == affine_terms.end()) - { - affine_terms.insert({i, coeff}); - } - else + auto ret = affine_terms.emplace(i, coeff); + if (!ret.second) { - it->second = coeff; + auto &iter = ret.first; + iter->second = coeff; } } void ExprBuilder::add_affine_term(const VariableIndex &i, CoeffT coeff)