Solidity developers often face challenges with gas costs during contract execution. Here are practical examples to illustrate how different operations affect gas usage:


💰 Basic Storage Operations

  1. Setting a value

    uint public x = 1; // 21000 gas
    
    storage_operation
  2. Reading a value

    x = block.timestamp; // 100 gas
    
  3. Using require()

    require(x > 0, "Value must be positive"); // 1000 gas
    

🌀 Gas-Hungry Loops

A loop can quickly exceed the block gas limit (e.g., 8 million gas). Example:

for (uint i = 0; i < 10000; i++) {
    balances[i] += 1; // Each iteration costs ~20000 gas
}

⚠️ Tip: Replace loops with for or while loops in Solidity 0.8.0+ for better optimization.

loop_example

🧮 Gas Cost Calculations

  • Storage writes: ~20000 gas per operation
  • SSTORE: 20000 + 5000 * number of storage slots
  • Math operations: ~100-1000 gas (e.g., +, *, **)

For deeper insights, check our Gas Optimization Guide.


📌 Practical Use Cases

  • Avoid excessive loops in token transfers
  • Use local variables to reduce SLOAD costs
  • Minimize array operations (e.g., delete arr)
solidity_gas_usage

Explore more examples in our Solidity 0.8.0 Reference.