How to Write Smart Contracts That Optimize Gas Spent on Ethereum

The following patterns were gathered from the paper “Under-Optimized Smart Contracts Devour Your Money.” These patterns increase gas costs and should be avoided.
Dead code
Dead code is code that will never run because it’s evaluation is predicated on a condition that will always return false.
Opaque predicate
The outcome of some conditions can be known without being executed and thus do not need to be evaluated.
Expensive operations in a loop
Due to the expensive SLOAD and SSTORE opcodes, managing a variable in storage is much more expensive than managing variables in memory. For this reason, storage variables should not be used in loops.
The fix for this pattern would be to create a temporary variable to represent the global variable and once the loop is complete, reassign the value of the temporary variable to the global variable.
Constant outcome of a loop
If the outcome of a loop is a constant that can be inferred during compilation, it should not be used.
Loop fusion
Occasionally in smart contracts, you may find that there are two loops with the same parameters. In the case that the loop parameters are the same, there is no reason to have separate loops.
Repeated computations in a loop
If an expression in a loop produces the same outcome in each iteration, it can be moved out of the loop. This is especially important when the variables(s) used in the expression are stored in storage.
a * b can be computed outside of the loop.Comparison with unilateral outcome in a loop
When a comparison is executed in each iteration of a loop but the result is the same each time, it should be removed from the loop.
Published at Fri, 17 Jan 2020 22:47:30 +0000
{flickr|100|campaign}
