Mapping Rule

Mapping variables are better in terms of gas savings when compared to array.

Example

pragma solidity ^0.8.17;

contract Array {
    uint256[] a;
    mapping(uint256 => uint256) b;

    constructor() {
        a.push() = 1;
        a.push() = 2;
        a.push() = 3;
        b[0] = 1;
        b[1] = 2;
        b[2] = 3;
    }

    function getArray(uint256 index) external view returns(uint256) {
        return a[index];
    }


    function get(uint256 index) external view returns(uint256) {
        return b[index];
    }
}

Calling function get would cost 1018 gas and calling function getArray would cost 3806 gas only, proving that the using mapping saves more gas than using array.

Test Environment

  • Compiler: solc 0.8.17
  • Testing Framework: Foundry

ETH saved over 100 transactions

100 tx * 30 gwei * 0.000000001 * (3806-1018) = 0.008541 ~= 0.008 ETH1

USD Saved over 100 transactions

  • At \$4000 / ETH: \$32
  • At \$3000/ETH: \$24
  • At \$2000/ETH: \$16
  1. Assumed gas price: 30 gwei 

results matching ""

    No results matching ""