0
0
Blockchain / Solidityprogramming~5 mins

Gas optimization with storage in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Storing data on blockchain costs gas, which is like paying for space. Optimizing storage helps save money and makes your smart contract efficient.

When you want to save money on deploying or running smart contracts.
When your contract needs to store many pieces of data but you want to reduce gas fees.
When you want your contract to run faster by reducing storage operations.
When you want to avoid unnecessary writes to blockchain storage.
When designing contracts that handle user data or state changes frequently.
Syntax
Blockchain / Solidity
// Example: Using smaller data types and packing variables
contract Example {
    uint128 smallNumber;
    bool flag;
    // Both variables fit in one storage slot, saving gas
}

Use smaller data types like uint8, uint16 instead of uint256 when possible.

Group variables of the same type together to pack them into fewer storage slots.

Examples
Using uint8 instead of uint256 saves storage space and gas.
Blockchain / Solidity
// Using smaller data types
uint8 age = 30;
uint8 score = 100;
Variables packed into one storage slot reduce gas cost.
Blockchain / Solidity
// Packing variables
contract Packed {
    uint128 a;
    uint128 b;
    bool c;
}
Only update storage if the value changes to save gas.
Blockchain / Solidity
// Avoid unnecessary storage writes
function update(uint256 newValue) public {
    if (storedValue != newValue) {
        storedValue = newValue;
    }
}
Sample Program

This contract uses smaller data types and updates storage only when needed to save gas.

Blockchain / Solidity
pragma solidity ^0.8.20;

contract GasOptimized {
    // Using smaller data types and packing
    uint128 public smallNumber;
    bool public flag;

    constructor(uint128 _num, bool _flag) {
        smallNumber = _num;
        flag = _flag;
    }

    // Update only if value changes
    function updateNumber(uint128 _num) public {
        if (smallNumber != _num) {
            smallNumber = _num;
        }
    }
}
OutputSuccess
Important Notes

Reading from storage is cheaper than writing, so minimize writes.

Use constants and immutable variables when possible to reduce storage.

Consider using events to log data instead of storing it if you don't need to read it on-chain.

Summary

Storing less data or packing variables saves gas.

Only write to storage when necessary.

Use smaller data types and group variables smartly.