From a5459a3aff760fa833c79b656e07ab0e8a80b470 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Mon, 31 Oct 2022 14:44:55 -0400 Subject: [PATCH] improve: Optimize BookSide::is_sorted --- src/lib/domain/BookSide.h | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/lib/domain/BookSide.h b/src/lib/domain/BookSide.h index 98ed0a60d..c5ee37d7e 100644 --- a/src/lib/domain/BookSide.h +++ b/src/lib/domain/BookSide.h @@ -594,16 +594,21 @@ void BookSideT::cover_top(std::size_t level) { template bool BookSideT::is_sorted(Side side, bool stop_on_first_empty_level) const { - PriceComp cmp(side); - for (std::size_t i = 0; i < max_depth(); i++) { + // CAUTION: the outer loop doesn't automatically increment 'i'. This is + // an optimization due to the fact that empty levels may be skipped. Make + // sure 'i' is ALWAYS incremented in the loop body. + for (std::size_t i = 0; i < max_depth() - 1;) { const auto &better = _book.at(i); if (better.is_empty()) { if (stop_on_first_empty_level) { return true; } + // Remember to increment 'i' + i++; continue; } - for (std::size_t j = i + 1; j < max_depth(); j++) { + std::size_t j = i + 1; + for (; j < max_depth(); j++) { const auto &worse = _book.at(j); if (worse.is_empty()) { if (stop_on_first_empty_level) { @@ -615,6 +620,9 @@ bool BookSideT::is_sorted(Side side, bool stop_on_first_empty_level) const { return false; } } + // Remember to increment 'i' + bts_assert(j > i); + i = j; } return true; }