2

Context

I have recently introduced a new constant getter in my contract, and I have thought that that it would lead to an increase in gas costs. Below you can find those snippets of code that reproduce the scenario from my actual code repository.

V1

struct MyStruct {
    address owner;
}

mapping(uint256 => MyStruct) internal myStructs;

modifier onlyOwner(uint256 id) {
    if (myStructs[id].owner != msg.sender) {
        revert Foo__NotAuthorized(msg.sender);
    }
    _;
}

V2

struct MyStruct {
    address owner;
}

mapping(uint256 => MyStruct) internal myStructs;

modifier onlyOwner(uint256 id) {
    if (getOwner(id) != msg.sender) {
        revert Foo__NotAuthorized(msg.sender);
    }
    _;
}

function getOwner(uint256 id) public view returns (address theOwner) {
    theOwner = myStructs[id].owner;
}

Question

There's also an additional method getBlockTimestamp onto which I applied the onlyOwner modifier. You can see the full code in this GitHub gist.

Now, here's the kicker. V1 and V2 cost the same amount of gas. My question is, why?

I expected V2 to cost more than V1 because it contains the same storage read, but on top of that it involves a call to the public function getOwner. Shouldn't that translate to additional opcodes in the bytecode representation of the smart contract?

Does Solidity "inline" the getter function?

1 Answer 1

3
+25

Because during compilation these 2 options will be represented as equal bytecode, because makes same logic.

Compiler see that function getOwner get ID and extract owner from mapping, same as 'myStructs[id].owner' line. Later compiler purge all unnecessary steps and makes for this 2 variants of code equal low-level calls.

You can deploy these 2 variants into blockchain, find them on etherscan and click decompilation to see almost human readable representation of how this variants was bytecoded.

Does Solidity "inline" the getter function?

yes, always when its possible, to maximally reduce future gas-costs for calls

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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