Skip to content

Instantly share code, notes, and snippets.

@buendiadas
Last active December 7, 2020 16:11
Show Gist options
  • Save buendiadas/dc1d84eb9467195d36e12b8fdb487206 to your computer and use it in GitHub Desktop.
Save buendiadas/dc1d84eb9467195d36e12b8fdb487206 to your computer and use it in GitHub Desktop.
Gas cost research on retrieving constants
pragma solidity ^0.6.8;
/// Trying to answer the question: Is it more expensive to check variable from a constant or from a memory variable?
/// The answer is that they both have near 0 gas costs (191 vs 213 gas) but checking from constant gives a lower value
contract externalContract {
uint256 storedConstant;
function getConstant() public returns (uint256) {
return 10**27;
}
// 20k gas
function storeConstant(uint256 _storedConstant) public {
storedConstant = _storedConstant;
}
}
contract constantGasChecker {
uint256 immutable private UINT_IMMUTABLE;
uint192 immutable private UINT_PRECISE;
uint256 private numVariable;
constructor(uint256 _numPrecision, uint256 _numVariable, uint192 _uintPrecise) public {
UINT_IMMUTABLE = _numPrecision;
numVariable = _numVariable;
UINT_PRECISE = _uintPrecise;
}
// Returns 257 gas
function checkWithConstant() public returns (uint256) {
return UINT_IMMUTABLE;
}
// Returns 197 gas
function checkWithConstantPrecise() public returns (uint192) {
return UINT_PRECISE;
}
// Returns 235 gas
function checkWithRunningVariable() public returns (uint256) {
return 10**27;
}
// Returns 1013 gas that comes mostly from an SLOAD (800gas)
function checkWithStoredVariable() public returns (uint256) {
return numVariable;
}
// 20k gas
function storeConstant(uint256 _storedConstant) public {
storedConstant = _storedConstant;
}
}
// 2194 gas
function getConstantFromExternalContract(address _externalContractAddress) public returns (uint256) {
return externalContract(_externalContractAddress).getConstant();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment