Avoid zero to non-zero storage writes

Published by Mario Oettler on

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.

FunctionGasTransaction costsExecution costs
Zero to Value497934329822234
One to Value30128261985134

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.

Categories:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select: