1

I am trying to understand the difference in gas cost between getTokenBalance for the two contracts below.

In Example 1 ERC20 is initialized once during the deployment of SomeContract as a part of the constructor, while in Example 2 ERC20 is initialized every time during getTokenBalance invocation.

Is there a siginificant difference between Example 1 and Example 2 below ?

Example 1:

contract SomeContract {
   ERC20 erc;

  constructor(tokenAddress){
      erc = ERC20(tokenAddress)
  }


   getTokenBalance(address owner) returns (uint){
      return erc.balanceOf(owner);
   }
}

Example 2:

contract SomeContract {

   getTokenBalance(address tokenAddress, address owner) returns (uint){
      ERC20 erc = ERC20(tokenAddress);
      return erc.balanceOf(owner);
   }

}
3

Gas costs are often dominated by storage. In this case, your first contract writes an address to storage, which costs 20,000 gas. The second contract doesn't do that.

1
  • Furthermore every byte (contract size) costs Oct 2 '19 at 18:05

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.