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)
As I understand,
Pure and View functions don't cost any gas to call if they're called
externally from outside
In this type of case, there won't be any transaction initiated because this will be like just querying the blockchain for its current state and nothing will be changed.
But they do cost gas if called internally by another function.
This means there's already a transaction to change the state of the blockchain, and that process of changing state need to use that pure function, say for calculations. Gas cost for a transaction depends on the number of EVM opcodes executed while completing it, so executing that pure function is also within that set of opcodes. That's why it's said that it costs gas.
Consider the following contract:
pragma solidity ^0.4.24;
contract PureFunctionTest {
uint state;
function addNumbers(uint a, uint b) public pure returns (uint) {
return a +b ;
}
function updateState(uint a, uint b) public {
uint c = addNumbers(a,b);
state = c;
}
function addThreeNumbers(uint a, uint b, uint c) public pure returns (uint) {
uint temp = addNumbers(a,b);
uint num = addNumbers(temp,c);
return num;
}
}
Just calling addNumbers
won't cost anything. But calling updateState
will cost including cost to addNumbers(a,b)
as well. Calling addThreeNumbers
won't cost gas even if it called addNumbers
internally since no transaction is needed throughout the function call.
Best Answer
View functions only use gas when they are called by non-view functions inside of the contract.
View functions don't consume gas because you are only making a call to your Node, so you're not asking every node on the chain to perform an action.
You can say that is free but you are limited by your node provider, if you want to make a lot of requests (usually more than 300k a month) you might need to pay your node provider. Or even if you have your own node you are paying for electricity and so on.