๐พ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
calldata
for Gas SavingsPractical 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:
After Optimization:
In the optimized version, the _tokens
parameter uses calldata
instead of memory
, leading to lower gas consumption as it minimizes data copying.
Recommended Mitigation Steps
Identify Memory Parameters: Go through your smart contracts to identify external functions with read-only parameters using
memory
.Replace with Calldata: Switch the data location of these parameters from
memory
tocalldata
for gas savings.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