Skip to content

Conditional optimization: true || x == true, false && y == false, etc. #6105

@scabug

Description

@scabug

There are four key optimizations that Mondrian's optimizer could make but doesn't.

Mondrian's optimizer is smart enough to turn if (true) a else b into a. To my delight, it is smart enough to do this even if true is inside a final val and not the literal true. This zeroth-order optimization is very helpful.

However, Mondrian's optimizer misses several key first-order optimizations that are quite useful.

  • true || x == true
  • false && y == false
  • true && x == x
  • false || y == y
  • x && true == x
  • y || false == y

Unfortunately, you have to be careful with the two remaining cases unless you can prove that x & y are side-effect free.

  • x || true == {x; true}
  • y && false == {y; false}

This is something that is pretty easy to encounter in performance-critical cases where you don't really want to have to rely on the JIT optimizer to be smart enough.

  class {
    final val extremeLogs = false
    for (tightLoop) {
      if (extremeLogs && logger.isTraceEnabled) { ... }
      ...
    }
  }

One would hope that the optimizer would actually be smart enough to recurse through boolean expressions and apply these transformations from the outside in. There are also some additional safe transformations like x && true && y == x && y.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions