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
Setting a value
uint public x = 1; // 21000 gas
Reading a value
x = block.timestamp; // 100 gas
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.
🧮 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
)
Explore more examples in our Solidity 0.8.0 Reference.