Gas Optimization
Learn tips for optimizing gas consumption.
Data storage and operations on the EVM cost gas, and given the immutability of Solidity code, there is no way to correct costly design decisions in our smart contracts. Following are some non-exhaustive best practices to optimize the gas usage of our contracts:
-
Avoid unnecessary on-chain computation.
-
Avoid arrays when possible.
-
Packing variables.
-
Use the right visibility modifiers for functions.
-
Short-circuiting conditionals.
Let’s go through each of these tips in detail.
Avoiding unnecessary on-chain computation
Programming in Solidity is a balancing act. It requires trade-offs between the high cost of transactions with:
Information security
Transparency
Decentralization
User incentives
In making these trade-offs, we should seek to move as much storage and computation off-chain as long as it is secure. We must put a lot of thought into the architecture of our contracts and the input and output of our functions.
pragma solidity >0.5.0;contract annualScoreBad {uint256 public totalScore;function saveScore(uint256[365] memory dailyScores) public {for (uint256 i = 0; i < 7; i++) {totalScore += dailyScores[i];}}}
The contract above stores the annual scores of the players of a game in the totalScore
variable, declared in line 3. Its value is input through the saveScore()
function in lines 4–8, which takes daily scores as input and stores their sum in totalScore
. In line 5, we can see that this requires an expensive iteration over each element of the array of daily scores.
Since the ...