๐Ÿ‘พGas Saving Technique 10: Calldata cheaper than memory

Introduction

Gas optimization plays a crucial role in making smart contracts efficient and cost-effective. In this context, choosing the appropriate data location for function parameters is vital. For read-only data in external functions, calldata proves to be a more gas-efficient choice than memory as it avoids unnecessary data copying and is cheaper in terms of gas cost.

Impact & Details

Understanding Gas Consumption

  • Memory Costs: Using memory for function parameters incurs extra gas cost due to data copying and allocation of memory space.

  • Calldata Efficiency: calldata is an immutable data area that holds function arguments. Itโ€™s more gas-efficient as it doesn't involve copying data and utilizes the non-modifiable, non-persistent space where function arguments are already stored.

How to Implement calldata for Gas Savings

Practical Example: Optimizing Data Location with calldata

Consider an example where you have a function that accepts an array of tokens as an argument:

Before Optimization:

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract TokenSweeper {
    function sweepTokens(IERC20[] memory _tokens) external {
        for (uint256 i = 0; i < _tokens.length; i++) {
            IERC20 token = _tokens[i];
            token.transfer(msg.sender, token.balanceOf(address(this)));
        }
    }
}

After Optimization:

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract TokenSweeper {
    function sweepTokens(IERC20[] calldata _tokens) external {
        for (uint256 i = 0; i < _tokens.length; i++) {
            IERC20 token = _tokens[i];
            token.transfer(msg.sender, token.balanceOf(address(this)));
        }
    }
}

In the optimized version, the _tokens parameter uses calldata instead of memory, leading to lower gas consumption as it minimizes data copying.

  1. Identify Memory Parameters: Go through your smart contracts to identify external functions with read-only parameters using memory.

  2. Replace with Calldata: Switch the data location of these parameters from memory to calldata for gas savings.

  3. Test: Rigorously test to ensure that the switch in data location does not affect the expected functionality of the contract while saving gas on transactions.

Conclusion

Switching to calldata for read-only data in external functions is a simple yet effective optimization technique for reducing gas consumption in smart contracts. The savings from this practice can be substantial over numerous transactions, especially for contracts with high traffic. After making these changes, it is imperative to perform detailed testing to ensure the contract operates as expected while utilizing less gas.

Last updated