Skip to content

Commit 3f470ca

Browse files
Artemiy-dvohi
authored andcommitted
QRM: optimize folding expr in applySwitchIndex
The original implementetion was translated by GCC to non-optimal bytecode with O(N) complexity. The patch fixes the issue and elaborates on the performance considerations in the code comment. Pick-to: 6.10 Change-Id: Ic53db8da769afb3c84c428b7198aecd098b0bb3b Reviewed-by: Volker Hilsheimer <volker.hilsheimer@qt.io> Reviewed-by: Artem Dyomin <artem.dyomin@qt.io>
1 parent 4e2639f commit 3f470ca

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

src/corelib/itemmodels/qrangemodel_impl.h

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,13 @@ namespace QtPrivate {
3636
template <typename Applier, size_t ...Is>
3737
void applyIndexSwitch(size_t index, Applier&& applier, std::index_sequence<Is...>)
3838
{
39-
// TODO: check if it's optimized properly on gcc.
40-
// A superficial research reveals that gcc may compile this code into a linear search,
41-
// whereas 'index' should be found in O(1) time like in a proper c++ switch.
42-
((Is == index ? applier(std::integral_constant<size_t, Is>{}) : static_cast<void>(0)), ...);
39+
// Performance considerations:
40+
// The folding expression used here represents the same logic as a sequence of
41+
// linear if/else if/... statements. Experiments show that Clang, GCC, and MSVC
42+
// optimize it to essentially the same bytecode as a normal C++ switch,
43+
// ensuring O(1) lookup complexity.
44+
static_cast<void>(((Is == index ? (applier(std::integral_constant<size_t, Is>{}), true) : false)
45+
|| ...));
4346
}
4447

4548
template <size_t IndexCount, typename Applier>

0 commit comments

Comments
 (0)