Zokyo Gas Savings
  • โ›ฝZokyo Gas Savings
  • ๐Ÿ“šTutorials
    • โœ”๏ธGas Saving Technique 1: Unchecked Arithmetic
    • โ›“๏ธGas Saving Technique 2: Immutable Variable
    • โœจGas Saving Technique 3: Double star ** inefficiency
    • ๐Ÿ’ฐGas Saving Technique 4: Cache Array Length
    • โฌ…๏ธGas Saving Technique 5: ++i costs less gas compared to i++
    • โš–๏ธGas Saving Technique 6: NOT operator ! cheaper than boolean FALSE
    • ๐ŸชกGas Saving Technique 7: Using Short Reason Strings
    • ๐ŸชตGas Saving Technique 8: Use Custom Errors instead of Revert Strings to save Gas
    • โœ’๏ธGas Saving Technique 9: Use Custom Errors instead of Revert Strings to save Gas
    • ๐Ÿ‘พGas Saving Technique 10: Calldata cheaper than memory
    • โ›”Gas Saving Technique 11: > 0 is less efficient than != 0 for unsigned integers
    • โž—Gas Saving Technique 12: SafeMath no longer needed
    • ๐Ÿ˜ฎGas Saving Technique 13: variables default to 0
    • ๐ŸงฑGas Saving Technique 14: struct layout/ variable packing
    • ๐Ÿ“žGas Saving Technique 15: Cache External Call
    • โœ๏ธGas Saving Technique 16: Early Validation before external call
    • ๐Ÿ˜ŽGas Saving Technique 17: Donโ€™t cache value that is used once
    • ๐Ÿ˜งGas Saving Technique 18: Redundant code
    • โœ…Gas Saving Technique 19: Early Validation before external call
    • โ›๏ธGas Saving Technique 20: Storage vs Memory read optimizations
    • โœ’๏ธGas Saving Technique 21: Unneeded If statements
    • ๐ŸŒ—Gas Saving Technique 22: >= is cheaper than >
    • ๐ŸŽ’Gas Saving Technique 23: Public to private constants
    • โน๏ธGas Saving Technique 24: Make unchanged variables constant/immutable
    • โฑ๏ธGas Saving Techniques 25: Redundant Access Control Checks
    • โžก๏ธGas Saving Technique 26: Shift Right instead of Dividing by 2
    • ๐ŸชƒGas Saving Tutorial 27: Efficient Boolean Comparison
    • ๐ŸคGas Saving Technique 28: && operator uses more gas
    • ๐Ÿ‘“Gas Saving Technique 29: x = x + y is cheaper than x += y
    • ๐Ÿ‘‚Gas Saving Technique 30: Using 1 and 2 rather than 0 and 1 saves gas
    • โšฝGas Saving Technique 31: Optimize Storage by Avoiding Booleans
    • ๐Ÿ”™Gas Saving Technique 32: Optimal Use of Named Return Variables in Solidity
    • ๐Ÿ›ข๏ธGas Saving Technique 33: Making Functions Payable for Optimized Gas Costs
    • โœ๏ธGas Saving Technique 34: Optimizing Storage References in Smart Contracts
    • โ›ฐ๏ธGas Saving Technique 35: Usage of uints/ints smaller than 32 bytes (256 bits) incurs overhead
    • ๐ŸŒช๏ธGas Saving Technique 36: Inlining Single Use Internal Functions for Savings
    • โ˜„๏ธGas Saving Technique 37: Switching from Public to External Functions for Savings
    • ๐ŸŽ†Gas Saving Technique 38: Upgrading Solidity Compiler to Improve Gas Efficiency and Security
    • ๐Ÿ•ถ๏ธGas Saving Technique 39: Avoiding Duplicated Code for Gas Savings
    • ๐Ÿ˜„Gas Saving Technique 40: Removal of Unused Internal Functions for Gas Savings
    • ๐Ÿ–‹๏ธGas Saving Tutorial 41: In-lining Single Use Modifiers For Gas Saving
    • โ›๏ธGas Saving Technique 42: `require` vs`assert`
Powered by GitBook
On this page
  1. Tutorials

Gas Saving Technique 4: Cache Array Length

PreviousGas Saving Technique 3: Double star ** inefficiencyNextGas Saving Technique 5: ++i costs less gas compared to i++

Last updated 1 year ago

Introduction

Efficiently managing gas consumption is pivotal when developing smart contracts. A subtle, yet effective technique to conserve gas during loop operations involves caching the length of arrays. This practice significantly reduces the number of read operations from the contract's storage, each of which would otherwise consume gas on every loop iteration.

Vulnerability Details & Impact

Understanding Gas Consumption

Reading from storage in Ethereum is expensive in terms of gas. When iterating through arrays using a for-loop without caching the array length, the length is read from storage during every iteration, incurring extra gas costs for each read operation. Specifically, reading the array's length at each iteration costs around 6 gas units (3 for mload and 3 to place memory_offset in the stack).

Gas Savings Through Reduction in Reads

Caching the array length in a variable prior to the loop's execution minimizes the number of read operations, thereby saving approximately 3 gas units per iteration. This can lead to significant gas savings, especially in scenarios where loops run through large arrays.

How to Implement Caching for Gas Savings

Practical Example: Caching Array Length to Reduce Reads

Letโ€™s look at an example to better understand this:

Before Optimization:

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

contract LoopGasOptimizer {
    uint[] public values;

    function calculateSum() public view returns (uint) {
        uint sum = 0;
        for (uint i = 0; i < values.length; i++) {
            sum += values[i];  // The length is read from storage on every iteration
        }
        return sum;
    }
}

After Optimization:

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

contract LoopGasOptimizer {
    uint[] public values;

    function calculateSum() public view returns (uint) {
        uint sum = 0;
        uint length = values.length;  // Cache the array length to reduce reads
        for (uint i = 0; i < length; i++) {
            sum += values[i];
        }
        return sum;
    }
}

In the optimized version, the number of read operations from storage is reduced by caching values.length into a variable, thereby saving gas on every loop iteration.

Recommended Mitigation Steps

  1. Identify Loops: Go through your smart contracts to find for-loops iterating over arrays.

  2. Cache Array Length: Cache the array length in a local variable before the loop commences.

  3. Use the Cached Length: Refer to the cached length variable in the loop condition, thus minimizing the number of storage read operations and saving gas.

Conclusion

While it might seem trivial, caching array lengths in loops is a valuable practice for reducing the number of read operations from storage, leading to gas savings. This practice is particularly crucial for contracts that deal with large arrays and frequent loop operations. Implementing this technique, combined with diligent testing, ensures your smart contracts are both efficient and functionally robust.

๐Ÿ“š
๐Ÿ’ฐ
Book an audit with Zokyo