Ethereum Solidity Gas Saving Tips

Photo by Zoltan Tasi on Unsplash

Ethereum Solidity Gas Saving Tips

Here is a simple tip on how to save gas when writing Solidity code

Accessing mapped values to save gas in Solidity

Originally posted on CryptoGuide.dev

Instead of accessing the same mapped value multiple times, use a local variable for reduced gas

Every time you access a mapped value, there is a fresh lookup of where that value is stored. This involves generating keccak256 hashes and accessing the storage.

It can save gas if you create a variable for the object you're accessing, for example:


pragma solidity >=0.8.4;

contract GasOptimizer {
    struct Person {
      uint age;
      uint highScore;
      uint numVisits;
    }
    mapping (address => Person) people;

    // 60449 gas
    function badExample() public {
      people[msg.sender].age = 20;
      people[msg.sender].highScore = 30;
      people[msg.sender].numVisits = 40;
    }

    // 60306 gas - slightly less, and it is doing the same thing
    function goodExample() public {
      Person storage person = people[msg.sender];
      person.age = 20;
      person.highScore = 30;
      person.numVisits = 40;
    }
}

See more gas optimization tips on CryptoGuide.dev or visit CryptoGuide.dev