Which is Test2 using less gas than Test1? (See below)

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();
    }
}

These contracts are the same.

The difference you saw is because you used the same Storage contract for the tests and the second write was cheaper. You would’ve observed the same difference if you used the same Test contract twice.

SSTORE is the opcode that writes to storage. The cost is higher when you change a storage slot from zero to nonzero, than when you change it from nonzero to nonzero.

For a detailed breakdown of these costs see https://github.com/wolflo/evm-opcodes/blob/main/gas.md#a7-sstore.

1 Like