Use Mappings Over Arrays in Some Cases

Published by Mario Oettler on

Last Updated on 24. March 2025 by Mario Oettler

In some cases, mappings can replace arrays to save gas. But it is important to know that mappings and arrays behave differently in certain circumstances. This sometimes makes it difficult to compare gas costs and can even lead to increased gas consumption.

While it is possible to return an array completely (either through a public variable or by returning it in a function), this is impossible with mappings. Arrays also allow values to be added by “push”. Mappings only allow values to be added by assigning them a unique key.

We use the following code example to compare the gas costs of arrays and mappings.

The following code shows the use of a mapping.

pragma solidity 0.8.29;

contract Mapping{
    mapping(uint256 => uint256) varA;

    function setValues() public{
        varA[0] = 1;
        varA[1] = 2;
        varA[2] = 3;
    }

    function getSingleValue(uint256 _a) public returns(uint256){
        return varA[_a];
    }
}

The following code uses an array.

pragma solidity 0.8.29;

contract Array{
    uint256[] varA;

    function setValues() public{
        varA.push(1);
        varA.push(2);
        varA.push(3);
    }

    function returnSingleValue() public returns(uint256){
        return varA[0];
    }

    function returnAllValues() public returns(uint256[] memory){
        return varA;
    }
}
Set VariablesRead single valueRead all values
Array1269192949935938
Mapping1009442753082618

You can see that storing values and reading single values is cheaper with a mapping than with an array.

However, it is important to note that read and write operations can be very different between arrays and mappings. For example, it is possible to retrieve the entire array by returning it in a function. This is impossible with a mapping. Here we always need the key for the value we want to get. This means that in our case we have only one read operation with an array, but three read operations with a mapping. This dramatically increases the cost of gas.

Categories: