Avoid zero to non-zero storage writes
Last Updated on 24. March 2025 by Mario Oettler
Initializing a storage variable is expensive. It costs 22,100 gas. Whereas writing to an already initialized storage variable costs only 5,000 gas. A storage variable is treated as uninitialized if it had never a value assigned to if a zero was assigned.
So, if you have a variable that for example switches between 0 and 1, you would always pay the higher gas fees if the value changes to 1.
A gas saving technique would be to let the variable switch between 1 and 2 for example.
Code Example
You can check this with the following example code:
pragma solidity 0.8.29;
contract Test{
uint256 public testVar;
function assignValue() public{
testVar = 2;
}
function setToZero() public{
testVar = 0;
}
function setToOne() public{
testVar = 1;
}
}
The following table shows the gas consumption in the cases zero to value and one to value.
Function | Gas | Transaction costs | Execution costs |
Zero to Value | 49793 | 43298 | 22234 |
One to Value | 30128 | 26198 | 5134 |
If contract creators want to save their users some gas they can “pre warm” the variables by initializing them during deployment. The downside is that this comes at a higher total cost for deployment. This tweak is in total more expensive than without. But it saves the first user some gas.