In the Ethereum Virtual Machine (EVM), gas is mapped to opcodes like SSTORE and SLOAD based on the computational and storage resources required to execute these operations. Specifically, SSTORE costs vary depending on the storage change—setting a zero value to a non-zero value incurs a higher cost, while overwriting an existing value or resetting to zero is cheaper. Conversely, SLOAD is a read operation and thus consumes less gas as it does not modify storage.
Breakdown of Gas Costs:
SSTORE (Storage Writes):
Writing a new value (from 0 to non-zero): Costs 20,000 gas.
Overwriting an existing value (non-zero to non-zero): Costs 5,000 gas.
Clearing a value (non-zero to 0): Refunds 15,000 gas due to reduced storage state.
SLOAD (Storage Reads):
Costs a flat 2,100 gas, as it simply reads from the trie structure in storage without modifying it.
Factors Impacting Gas:
State Change Complexity: Modifying storage involves writing to disk-backed storage, which is expensive.
Gas Refunds: Clearing storage results in partial gas refunds to incentivize storage optimization.
Cold vs. Warm Access: EIP-2929 introduced additional gas costs for "cold" storage slots, which are accessed for the first time in a transaction.
Example:
solidity
Copy
Edit
contract GasExample {
uint public value;
function writeStorage(uint _value) public {
value = _value; // SSTORE operation
}
function readStorage() public view returns (uint) {
return value; // SLOAD operation
}
}
Writing to value incurs SSTORE costs based on the value's previous state, while reading value incurs the lower SLOAD cost. Understanding these gas mappings is key to optimizing smart contract design.