Gas Costs for Solidity Built-in Functions

41 阅读1分钟

Gas Costs for Solidity Built-in Functions

OperationGas CostNotes
Simple Arithmetic
+, -, *, /, %3–5 gasBasic integer math. Division is more expensive.
** (exponentiation)10–100+ gasCost scales with exponent size.
++, --3–5 gasIncrement/decrement.
Storage Operations
SSTORE (write new value)20,000–22,100 gas22,100 for new storage slot, 20,000 for updating existing non-zero value.
SSTORE (set to zero)500–5,000 gasGas refund may apply.
SLOAD (read storage)2,100 gasReading from storage.
Memory Operations
MLOAD (read memory)3 gas
MSTORE (write memory)3–6 gas
Ether Transfers
address.transfer()2,300 gas stipendFixed gas, reverts on failure.
address.send()2,300 gas stipendReturns bool, does not revert.
address.call{value: x}()All remaining gasFlexible but risky (reentrancy).
Hashing & Cryptography
keccak256()30–60 gasCost depends on input size.
sha256()60+ gasMore expensive than keccak256.
Contract Operations
new Contract()32,000+ gasBase cost + deployment bytecode execution.
selfdestruct(address)5,000 gasRefunds may apply.
Logging (Events)
emit Event()375–2,000+ gasBase cost + 375 gas per topic + 8 gas per byte of data.
Control Flow
require() / revert()10–30 gasEarly termination with message costs more.
assert()10–30 gasSimilar to require but for internal errors.
Function Calls
External call (contract.func())700+ gasBase cost + function execution.
Internal call (this.func())100–300 gasCheaper than external calls.

Key Notes

  1. Gas Costs Are Approximate:
    • Actual costs depend on compiler optimizations, EVM upgrades, and context (e.g., cold vs. warm storage access).
  2. Storage vs. Memory:
    • Storage (SSTORE/SLOAD) is 1,000x+ more expensive than memory (MSTORE/MLOAD).
  3. Ether Transfers:
    • transfer and send limit gas to 2,300 (preventing reentrancy but risky for contracts).
    • call forwards all gas (use with checks-effects-interactions).
  4. Refunds:
    • Setting storage to zero (SSTORE to 0) may refund up to 4,800 gas.

Example Gas Calculation

function example() public {
    uint a = 1;          // ~3 gas (memory write)
    a += 1;              // ~3 gas (arithmetic)
    emit Log(a);         // ~500 gas (1 topic + data)
    require(a > 0, "!"); // ~25 gas
}

Total: ~531 gas (excluding function call overhead).


For precise gas estimation, use:

  • Hardhat: hardhat-gas-reporter plugin.
  • Remix: Gas meter in the debugger.
  • Etherscan: Check gas used in confirmed transactions.