There are several rules we can add to $switch to improve its constant folding:
- When a case is a constant, and false, we can remove that case.
- When a case is a constant, and true, we can turn that case into the default, and remove all subsequent cases.
- When there are no cases, we can replace the $switch with its default.
Alternatively, we could desugar $switch to chain of $cond expressions; then
SERVER-55297 would have the same effect as the above three rules. This approach makes the rewrites simpler but results in more calls to evaluate().
Either option would let $bucket take advantage of a $group-by-constant optimization, since $bucket desugars to $group + $switch. (Although I don't think we have a $group-by-constant optimization currently.)
- is related to
SERVER-55297 Short circuit $cond if condition is a constant
- related to
SERVER-70190 ExpressionSwitch::optimize() can leave expression tree in an invalid state leading to invariant failure