I was wondering what is the most efficient way (and why), to use variables in memory for function calls with regards to A and B?

A) Like this:

 function checkBalance() public view returns (uint256) {
        address _payee = msg.sender;
        return balanceOf(_payee);

B) Or like this:

     function checkBalance(address beneficiary) public view returns (uint256) {
            return balanceOf(beneficiary);
  • It is unclear what the modifier have to do with the question. – goodvibration Oct 30 '19 at 14:31
  • I removed it, you're correct. – NowsyMe Oct 30 '19 at 14:59
  • 2
    Those functions are not the same: a) it returns the sender balance, b) it returns the balance of any address so it is hard to compare. You have to take into consideration other things like that using a lot of local variables might cause the error message "stack too deep". – Ismael Oct 30 '19 at 16:46
  • But in A, why would one want to create a local variable to save msg.sender? why not just return msg.sender and remove the payee variable? are the situations where the above pattern is recommended? – NowsyMe Oct 30 '19 at 16:55

So if you mean if there is a serious penalty for instantiating a variable in memory rather than using it directly, no, there's not. Actually probably there will be no penalty at all if the compiler is smart enough, which shouldn't be a problem in cases like this one (specially with optimization enabled in the solidity compiler).

That being said, I'd only store a variable in a local one for the sake or readability, which is in my opinion not justified in your case, so B would be preferred for both simplicity and readability, but I guess it's a matter of taste.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.