Técnicas de economia de gás

# Técnicas de economia de gás

Algumas técnicas de economia de gás:

  • Substituindo memory por calldata
  • Carregar variável de estado na memória
  • Substitua i++ por ++i
  • Cache de elementos da matriz
  • Short circuit
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

// gas golf
contract GasGolf {
    // início - 50908 gas
    // usando calldata - 49163 gas
    // carregar variáveis de estado na memória - 48952 gas
    // short circuit - 48634 gas
    // incrementos de loop - 48244 gas
    // gravar tamanho do array - 48209 gas
    // carregar elementos do array na memoria - 48047 gas
    // uncheck i overflow/underflow - 47309 gas


    uint public total;

    // início - sem otimizar consumo de gas
    // function sumIfEvenAndLessThan99(uint[] memory nums) external {
    //     for (uint i = 0; i < nums.length; i += 1) {
    //         bool isEven = nums[i] % 2 == 0;
    //         bool isLessThan99 = nums[i] < 99;
    //         if (isEven && isLessThan99) {
    //             total += nums[i];
    //         }
    //     }
    // }

    // otimizando consumo de gas
    // [1, 2, 3, 4, 5, 100]
    function sumIfEvenAndLessThan99(uint[] calldata nums) external {
        uint _total = total;
        uint len = nums.length;

        for (uint i = 0; i < len; ) {
            uint num = nums[i];
            if (num % 2 == 0 && num < 99) {
                _total += num;
            }
            unchecked {
                ++i;
            }
        }

        total = _total;
    }
}

# Teste no Remix

Last Updated: 22/01/2024 22:26:13