12

I have a function that does not read or modify contract's state:

contract C {

    function add(uint a, uint b) public returns (uint) {
        uint res = a + b;
        return res;
    }

}

Does it make sense to use pure/view modifier? I mean, will the function use less gas after that or what is the reason to use it?

1

1 Answer 1

24

If you can make your function pure, you should always make it pure. Otherwise, if you can make your function view, you should always make it view.

Advantages:

  • If you make your function pure or view, you can call it for example through web3.js without needing a transaction, without any gas cost and without confirmation delay.

  • Currently, it will not reduce gas cost when executing on the EVM. However, in the future it may help the Solidity compiler to optimize your program.

  • It will prevent you from accidentally reading or writing contract state in functions where you don't want to.

Disadvantages:

(none)

2
  • It's 2022. Are pure and view functions optimized by Solidity? Commented Jul 12, 2022 at 11:25
  • Only the last advantage you have listed makes sense. The first 2 are automatically determined by the solidity compiler.
    – Freddie
    Commented Feb 1, 2023 at 8:24

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.