Go

Go

Made by DeepSource

Reorder operands for optimization GO-P3001

Performance
Critical
Autofix

Sometimes reordering the operands can save computational resources because of the properties of operators like "&&" (AND) or "||" (OR) in a binary expression.

For logical operators ("AND" and "OR"), if the evaluation of an expression exits before complete evaluation, it is known as "short-circuiting." A short circuit happens when the result is clear even before the complete evaluation of the expression, and the result is returned, avoiding unnecessary evaluation and leading to efficient processing.

We recommend writing logical expressions such that one takes advantage of short-circuiting and avoids evaluating operands if not necessary hence saving computational resources.

Bad practice

// "caller" is call expression and y is of bool type
// Here caller(x, y) is evaluated and based on the evaluation
// it decides to go to next operand.
if caller(x, y) || y { ... }

Recommended

// "caller" is call expression, and y is of bool type
// Here y is evaluated, i.e., generally computationally cheaper
// to consider compared to call expressions.
//
// If y == true, then the result of the expression would result
// in `true` no matter what other operands evaluate to. Hence,
// no need to evaluate caller(x, y) anymore. Hence, reordering
// helped.
if y || caller(x, y) { ... }