Solidity

獲取儲存的值以用於功能邏輯

  • July 26, 2019

通過呼叫函式呼叫私有變數而不是直接呼叫私有變數來將儲存的數據提取到其他函式中是否有任何好處?什麼是最佳實踐?

例子

contract PlayerExample {

   uint private maximumPlayers

   uint private players;

   function playersCount() public view returns (uint) {
       return players;
   }

   function playerSlotsLeft() public view returns (uint) {
       return (maximumPlayers - players);
       //or is it better to do 
       //return (maximumPlayers - playersCount());
   }
}

從 gas 的角度來看——特別是,如果它作為交易的一部分被另一個合約呼叫,而不僅僅是直接呼叫——那麼在堆棧上沒有另一個函式呼叫將會更便宜:

pragma solidity ^0.5.1; 

contract PlayerExample {
   uint private maximumPlayers = 10;
   uint private players = 5;

   function playerSlotsLeft() public view returns (uint) {
       return (maximumPlayers - players);
   }
}
  • 交易成本:21874
  • 執行成本:602

pragma solidity ^0.5.1; 

contract PlayerExample {
   uint private maximumPlayers = 10;
   uint private players = 5;

   function playersCount() public view returns (uint) {
       return players;
   }

   function playerSlotsLeft() public view returns (uint) {
       return (maximumPlayers - playersCount());
   }
}
  • 交易成本:21931
  • 執行成本:659

引用自:https://ethereum.stackexchange.com/questions/73316