solidity – How to Optimize Gas Usage with View and Pure Functions?

gaspuresolidityview

I know similar questions have been asked before however I could not find an good explanation for the following,

In one of the tutorial it says:

Pure and View functions don't cost any gas to call if they're called
externally from outside the contract. But they do cost gas if called
internally by another function.

  • Why do they need gas if they don't update anything?
  • How does read cost gas?
  • Isn't it read from my local blockchain?

Best Answer

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.