BudiBadu Logo
Samplebadu

Solidity by Example: Arrays

0.8.x

Working with Solidity arrays through this code example demonstrating dynamic and fixed-size array declarations, push and pop operations, the delete keyword behavior, length property access, and gas considerations for large datasets.

Code

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

contract ArrayExample {
    // Dynamic array
    uint256[] public arr;
    
    // Fixed size array
    uint256[5] public fixedArr;

    function push(uint256 _i) public {
        // Appends to the end
        arr.push(_i);
    }

    function pop() public {
        // Removes last element
        arr.pop();
    }

    function getLength() public view returns (uint256) {
        return arr.length;
    }

    function remove(uint256 _index) public {
        // Delete resets the value to default (0), length stays same
        delete arr[_index];
    }
    
    // Returning an entire array (use with caution due to gas)
    function getAll() public view returns (uint256[] memory) {
        return arr;
    }
}

Explanation

Solidity supports both compile-time fixed-size arrays T[k] with a predetermined length k, and dynamic arrays T[] that can grow or shrink at runtime. Dynamic storage arrays provide push() and pop() members for appending or removing elements from the end. The push() operation is O(1) in gas cost per element, with approximately 20,000 gas for writing to a new storage slot and 5,000 gas for overwriting existing values.

The delete keyword resets an element at a specific index to its default value (0 for uint, false for bool) but does not change the array length or shift subsequent elements. To truly remove an element and shrink the array, you must manually implement a "swap and pop" pattern: move the last element to the deleted position, then pop the array. This avoids expensive shifting operations that would require rewriting multiple storage slots.

Be extremely careful when iterating over or returning large arrays. Loops that grow with array size can exceed the block gas limit (currently around 30 million gas), causing transactions to fail. Best practices for array usage include:

  • Prefer mappings over arrays for large datasets requiring direct key access
  • Use fixed-size arrays when maximum length is known at compile time
  • Implement pagination or batch processing for large collections
  • Consider the swap-and-pop pattern for efficient element removal
  • Avoid returning entire arrays in functions that might be called externally

Code Breakdown

6
uint256[] declares a dynamic array that can grow indefinitely.
9
uint256[5] creates a fixed-size array with exactly 5 elements.
13
arr.push(_i) adds element to end, increasing length by 1.
27
delete arr[_index] resets value to 0 but doesn't remove the slot.