diff --git a/CHANGELOG.md b/CHANGELOG.md index 5718e34223f..f220e6f6c50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ ### Fixed * ([#????](https://github.com/realm/realm-core/issues/????), since v?.?.?) * Converting local realm to sync'd realm crashes if an embedded object is null ([#6294](https://github.com/realm/realm-core/issues/6294), since v11.9.0) +* Fixed performance degradation on SubQueries ([#6327](https://github.com/realm/realm-core/issues/6327), since v6.0.0) ### Breaking changes * None. diff --git a/src/realm/query_expression.hpp b/src/realm/query_expression.hpp index 93dd744995e..6891531a100 100644 --- a/src/realm/query_expression.hpp +++ b/src/realm/query_expression.hpp @@ -3866,7 +3866,10 @@ class SubQueryCount : public Subexpr2 { { std::vector links = m_link_map.get_links(index); // std::sort(links.begin(), links.end()); - m_query.init(); + if (!m_initialized) { + m_query.init(); + m_initialized = true; + } size_t count = std::accumulate(links.begin(), links.end(), size_t(0), [this](size_t running_count, ObjKey k) { const Obj obj = m_link_map.get_target_table()->get_object(k); @@ -3893,9 +3896,17 @@ class SubQueryCount : public Subexpr2 { return make_subexpr(*this); } + SubQueryCount(const SubQueryCount& other) + : m_query(other.m_query) + , m_link_map(other.m_link_map) + , m_initialized(false) + { + } + private: Query m_query; LinkMap m_link_map; + bool m_initialized = false; }; // The unused template parameter is a hack to avoid a circular dependency between table.hpp and query_expression.hpp.