Skip to content

Instantly share code, notes, and snippets.

@karmacoma-eth
Created February 8, 2022 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karmacoma-eth/37846ffa6d715142f4ebe0c4555226aa to your computer and use it in GitHub Desktop.
Save karmacoma-eth/37846ffa6d715142f4ebe0c4555226aa to your computer and use it in GitHub Desktop.
Is it cheaper to check if a new value is different before storing it?
// SPDX-License-Identifier: Unlicense
pragma solidity >=0.8.0;
contract CheckBeforeStore {
event Log(address);
bytes32 stored;
function setUp() public {
stored = keccak256(abi.encode(address(this)));
}
function justStore(bytes32 newValue) public {
stored = newValue;
}
function checkThenStore(bytes32 newValue) public {
if (stored != newValue) {
stored = newValue;
}
}
// [PASS] testJustStoreWithSameValue() (gas: 495)
function testJustStoreWithSameValue() external {
justStore(stored);
}
// [PASS] testCheckThenStoreWithSameValue() (gas: 460)
function testCheckThenStoreWithSameValue() external {
checkThenStore(stored);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment