0

I tested the following contract in remix, but the gas used appears to be different than the following article, why could this be?

My contract:

pragma solidity 0.8.16;

contract Math {
    uint public num;
    // 30494
    function add1() external returns (uint) {
        num++;
    }
    // 30551
    function add2() external returns (uint) {
        ++num;
    }
    // 30650
    function add3() external returns (uint) {
        num += 1;
    }
    // 30661
    function add4() external returns (uint) {
        num = num + 1;
    }
}

Theirs: https://dev.to/jamiescript/gas-saving-techniques-in-solidity-324c

//SPDX-License-Identifier:MIT;

pragma solidity ^0.8.3;

contract One{
   uint256 public number;
  //Gas used : 43800
   function incrementByOne() public returns (uint256){
      number += 1;
      return number;
   }
}

contract Two{
   uint256 public number;
   //Gas used : 43787
   function incrementByOne() public returns (uint256){
     number = number + 1;
     return number;
   }
}

contract Three{
   uint256 public number;
   //Gas used : 43634
   function incrementByOne() public returns (uint256){
       return number++;
   }
}

contract Four{
   uint256 public number;
   //Gas used : 43628
   function incrementByOne() public returns (uint256){
       return ++number;
   }
}

1 Answer 1

1

Few reasons for the difference in gas usage between your contract and the one in the article:

  • Although all these operations are identical, evm compiler doesn’t treat them the same way
  • Your contract uses 'external' while the article's contract uses 'public' for function visibility, which could cause variations in gas usage.
  • Unlike the article's contract, you're not returning any value in your functions, which might cause a difference in gas usage.
  • The solidity version is different on both contracts, which can also alter the gas usage.
  • Function names can also impact gas consumption. For more details, you can check out this article: https://medium.com/joyso/solidity-how-does-function-name-affect-gas-consumption-in-smart-contract-47d270d8ac92

If you're looking to optimize further, you can also use unchecked {} for your math operations if you're sure that no overflow/underflow is possible here.

I'll suggest you to read that article if you want to optimize your contract further: https://betterprogramming.pub/the-ultimate-100-point-checklist-before-sending-your-smart-contract-for-audit-af9a5b5d95d0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.