typestar

Loops and gas in Solidity

Every pass costs gas; bounded arrays keep loops honest.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// Loops cost gas per pass, so bounded arrays keep them honest.
contract WeighStation {
    uint256[] public cratesKg;

    function log(uint256 kg) external {
        cratesKg.push(kg);
    }

    function total() external view returns (uint256 sum) {
        uint256 n = cratesKg.length;
        for (uint256 i = 0; i < n; i++) {
            sum += cratesKg[i];  // named return accumulates
        }
    }

    function heaviest() external view returns (uint256 best) {
        for (uint256 i = 0; i < cratesKg.length; i++) {
            if (cratesKg[i] > best) best = cratesKg[i];
        }
    }
}

How it works

  1. Caching length before the loop saves repeated reads.
  2. A named return like uint256 sum accumulates directly.
  3. Unbounded growth makes total() costlier every push.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
560
Tokens
126
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 126 seconds.

Type this snippet

Step 2 of 3 in Data & gas, step 15 of 28 in Language basics.

← Previous Next →