3

I've got a very simple contract. It narrows down and measures cost of loading a storage variable:

pragma solidity ^0.7.6;
contract Bench {
    
    uint256 public data;
    
    function increment() public {
        uint256 gasUsed = gasleft();
        uint256 dataLocal = data;
        gasUsed -= gasleft();
        dataLocal += gasUsed;
        data = dataLocal;
    }
    
}

It generates an unsurprising assembly:

(...)
      GAS           gasleft()
      PUSH 0            uint256 dataLocal
      SLOAD             data
      SWAP1             uint256 gasUsed = gasleft()
      SWAP2             uint256 gasUsed = gasleft()
      POP           
      GAS           gasleft()
(...)

The measured gas usage according to the yellow paper should be 213:

PUSH    - 3
SLOAD   - 200
SWAP1   - 3
SWAP2   - 3
POP     - 2
GAS     - 2  

A simple Remix test shows the measured gas:

    function checkFailure() public {
        Bench bench = new Bench();
        bench.increment();
        Assert.equal(bench.data(), 0, "GAS USED");
    }

The printed result is 813, exactly 600 more than expected. Why? How to reduce that?

3
  • 2
    Does this answer your question? Gas cost of setting a state-variable to the same value – goodvibration Dec 16 '20 at 21:38
  • No, the other question is about SSTORE. Some SSTORE operations happen to have the same cost as SLOAD, but that's a far stretch. – CodeSandwich Dec 17 '20 at 0:52
  • Ahhh, you're right. Funny enough though, the answer to that other question is exactly the same (and the gas-measurement in your question is almost the same as the gas-measurement in the other question). – goodvibration Dec 17 '20 at 1:02
4

EIP-1884 changed the cost of an SLOAD from 200 to 800, which explains why you are seeing exactly 600 more than expected.

It looks like the yellow paper has not been updated to reflect this change.

Edit: I have opened a PR on the yellow paper repository to resolve this issue.

3
  • 1
    Nice catch, Shane. – Rob Hitchens Dec 16 '20 at 19:49
  • 1
    @RobHitchens: Almost the exact same question was answered here a while back. – goodvibration Dec 16 '20 at 21:39
  • 1
    And also here, by @eth himself (or herself). – goodvibration Dec 16 '20 at 21:40

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.