Hi there, I did some test on gas usage for two patterns of using an interface. See the following code for details. It turns out Method 1: IStorage(address).setVal(100)
costs less gas than iStorage= IStorage(address);
, Method 2: iStorage.setVal(100)
.
Method 1 takes 24,773 gas on BSC Testnet.
Method 2 takes 43,973 gas on BSC Testnet.
Also I would think it costs more gas in deploying contract Test than Test2, but it turns out they cost almost the same.
Any in-depth explanation is highly appreciated. Thanks.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
contract Storage {
uint256 private val;
function setVal(uint256 val_) public {
val = val_;
}
function getVal() public view returns(uint256) {
return val;
}
}
interface IStorage {
function setVal(uint256 val_) external;
function getVal() external view returns(uint256);
}
contract Test {
IStorage iStorage;
constructor(address addr) {
iStorage = IStorage(addr);
}
function setVal(uint256 val_) public {
iStorage.setVal(val_);
}
function getVal() public view returns(uint256) {
return iStorage.getVal();
}
}
contract Test2 {
address private addr;
constructor(address addr_) {
addr = addr_;
}
function setVal(uint256 val_) public {
IStorage(addr).setVal(val_);
}
function getVal() public view returns(uint256) {
return IStorage(addr).getVal();
}
}