Gas-Saving Patterns

The following are patterns you can make use of in your code to reduce gas consumption.

Short-circuiting

Short-circuiting is a strategy we can make use of when an operation makes use of either || or && . This pattern works by ordering the lower-cost operation first so that the higher-cost operation may be skipped (short-circuited) if the first operation evaluates to true .

Example from stack exchange.

Unnecessary libraries

Libraries are often only imported for a small number of uses, meaning that they can contain a significant amount of code that is redundant to your contract. If you can safely and effectively implement the functionality imported from a library within your contract, it is optimal to do so.

Example with a redundant library

Example without the library

Explicit function visibility

Explicit function visibility can often provide benefits in terms of smart contract security as well as gas optimization. For example, explicitly labeling external functions forces the function parameter storage location to be set as calldata , which saves gas each time the function is executed.

Proper data types

In Solidity, some data types are more expensive than others. It’s important to be aware of the most efficient type that can be used. Here are a few rules about data types.