Gas and it's consumption in Solidity Programming

Viewed 63

I have been trying to learn Solidity lately.

But as a Developer who has only C++, Java Development experience.

I am not able to understand the logic of Gas in Solidity.

  1. Why is it needed?
  2. What are the points that result in its consumption?
  3. How to reduce its consumption?
1 Answers

EVM-based networks are usually public and open to anyone. They also have limited capacity of how many transactions they're able to process.

Having to pay for a transaction mitigates the amount of spam transactions that would otherwise be flooding the network, making it unusable for regular users.


Generally speaking, working with persistent storage is 100s and 1000s of times more expensive compared to working with nonpersistent data locations such as memory (scoped only for each transaction, then it's unallocated).

A rule of thumb for gas usage optimization is to access storage as few as possible. For example instead of making two reads to the storage, you can make one read, and store the data in memory variable (that is much cheaper to read).

uint8 number;

function isNumberValid() external returns (bool) {
    return (
        number >= 100  // storage read
        && number <= 200  // storage read
    );
}

"Two storage reads" (above) are more expensive than "one storage read, one memory store, and two memory reads" (below).

uint8 number;

function isNumberValid() external returns (bool) {
    uint8 _number = number; // storage read, memory store
    return (
        _number >= 100  // memory read
        && _number <= 200  // memory read
    );
}

There is a fairly extensive list of each operation gas cost in the (regularly updated) Yellow paper, appendix G and H, currently on pages 27 and 28.

Related