Factoring expressions

In IBM® Enterprise COBOL Version 4 Release 2 Performance Tuning, it says: "For evaluating arithmetic expressions, the compiler is bound by the left-to-right evaluation rules for COBOL. In order for the optimizer to recognize constant computations (that can be done at compile time) or duplicate computations (common subexpressions), move all constants and duplicate expressions to the left end of the expression or group them in parentheses."

The V6 compiler factors expressions as a part of optimization and no longer requires this type of factoring to be done at the source code level as was recommended in V4. However, this only applies within a single expression. Consider the following example, which shows two ways of summing the total cost of a set of items and applying a discount:

MOVE ZERO TO TOTAL
PERFORM VARYING I FROM 1 BY 1 UNTIL I = 10
COMPUTE TOTAL = TOTAL + ITEM(I) * DISCOUNT
END-PERFORM
MOVE ZERO TO TOTAL
PERFORM VARYING I FROM 1 BY 1 UNTIL I = 10
COMPUTE TOTAL = TOTAL + ITEM(I)
END-PERFORM
COMPUTE TOTAL = TOTAL * DISCOUNT

The first block of code performs ten multiplications, while the second block of code only performs one. The second block of code is therefore more efficient. The V6 compiler does not perform this type of factoring across loops. It's done at the source code level.