Contract-Development

新價值與現有價值相同的 SSTORE 是否會消耗汽油?

  • December 13, 2020

例如(在 Vyper 中):

@external
def foo(bar: uint256):
 self.baz = bar

foo(3)
foo(3) # Is the gas cost here still 5000?

這樣做更好嗎?

def foo(bar: uint256):
 if self.baz != bar: # Will this check save gas from unnecessary SSTORE's
     self.baz = bar

以下測試意味著儲存相同值的成本是 800 個氣體單位:

Solidity 合約:

pragma solidity 0.6.12;

contract MyContract {
   uint256 public gasUsed;
   uint256 public storageSlot;
   function func(uint256 x) public {
       storageSlot = x;
       uint256 gasLeft = gasleft();
       storageSlot = x;
       gasUsed = gasLeft - gasleft();
   }
}

松露 5.x 測試:

const MyContract = artifacts.require("MyContract");

contract("MyContract", accounts => {
   it("test", async () => {
       const myContract = await MyContract.new();
       for (let x = 0; x < 10; x++) {
           await myContract.func(x);
           const gasUsed = await myContract.gasUsed();
           console.log(gasUsed.toString());
       }
   });
});

每次迭代的列印輸出為 816。

假設gasleft()合約函式最後一行的操作花費了 16 個 gas 單位,儲存相同值的成本似乎是 800 個 gas 單位。

引用自:https://ethereum.stackexchange.com/questions/90318