Ether and Gas

Gas Optimization Techniques

Beginner Level

Gas optimization techniques help reduce transaction costs and improve the efficiency of smart contracts.

1) Use memory and calldata

  • Avoid unnecessary storage writes.
  • Temporary variables in memory are cheaper.

function sum(uint256[] memory arr) public pure returns (uint256) { ... }

2) Minimize storage reads and writes

  • Read once, update once.

uint256 temp = storedData;
temp += 1;
storedData = temp;

3) Use immutable and constant

  • constant and immutable variables reduce storage gas.

uint256 public constant MAX = 100; // No storage cost

4) Pack variables

  • Fit smaller types together into one 32-byte storage slot.

struct Packed {
    uint8 a;
    uint8 b;
    uint16 c; // All fit in one slot
}

5) Avoid loops on storage arrays

  • Loops over large arrays are expensive; prefer mappings.

6) Use events instead of storage

  • Log data using events when permanent storage is not required.

Summary table

Feature Description
Payable functions Functions that can receive Ether
transfer Sends Ether, reverts on failure, 2300 gas
send Sends Ether, returns success bool, 2300 gas
call Sends Ether, forwards all gas, returns success and data
Gas Measures computational effort
Gas limit Maximum gas user allows for a transaction
Gas optimization Use memory/calldata, minimize storage writes, pack variables, use constants