Optimal stack evaluation of a binary expression tree

ID: optimal-stack-evaluation-of-a-binary-expression-tree

Suppose each subtree of a binary expression tree is evaluated completely before its sibling, leaves one result on an operand stack, and is not spilled or interleaved. If the child depths are , evaluating the first child needs slots and keeping its result while evaluating the second needs . Reversing the order gives . If either order preserves the expression's meaning, the minimum is when and when . For example, if , integrality gives , so evaluating the deeper child first attains the lower bound . If , the second child needs its own slots plus one saved result regardless of order. Induction over the binary expression tree proves optimality in this evaluation model.
For a noncommutative operator, an instruction swapping the top two stack entries or a reverse-operand opcode permits the same ordering while preserving operand positions. Reordering still requires absence of order-sensitive side effects. Reassociation and interleaving are separate transformations and are not part of this optimality claim.

New to topics? Read the docs here!