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?
Best Answer
If you can make your function
pure
, you should always make itpure
. Otherwise, if you can make your functionview
, you should always make itview
.Advantages:
If you make your function
pure
orview
, 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)