April 30, 2026

How to Write Smart Contracts That Optimize Gas Spent on Ethereum

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 is code that will never run because it’s evaluation is predicated on a condition that will always return false.

If x is less than 1, it cannot be greater than 2, so line 4 will never be executed.

The outcome of some conditions can be known without being executed and thus do not need to be evaluated.

If x is greater than 1, it is certainly greater than 0, so line 3 is redundant.

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.

Each iteration of the loop requires costly storage management.

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.

Assign the value to a temporary variable.

If the outcome of a loop is a constant that can be inferred during compilation, it should not be used.

The return value will always be the same.

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.

These loops are identical and can thus be combined.

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.

The product of a * b can be computed outside of the 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.

The condition on line 4 has the same outcome each time, so it should be removed from the loop.

Published at Fri, 17 Jan 2020 22:47:30 +0000

{flickr|100|campaign}

Previous Article

How to Write Smart Contracts That Optimize Gas Spent on Ethereum

Next Article

How to Write Smart Contracts That Optimize Gas Spent on Ethereum

You might be interested in …