๐ŸŒช๏ธGas Saving Technique 36: Inlining Single Use Internal Functions for Savings

Introduction: Solidity offers both public, private, and internal function visibility. While internal functions offer flexibility in terms of reusability and code organization, if they are only called once, there can be an added overhead. In such cases, inlining these functions can save on the gas cost.


Concept:

  1. Function Calls Overhead: Every function call, even internal ones, comes with a bit of overhead in the EVM.

  2. Inlining: This is a compiler optimization technique where the function's code is expanded in place rather than being called, thereby saving on the overhead associated with the function call.


Examples & Recommendations:

Problem: Having an internal function that's only called once in the contract. Solution: Instead of keeping it as a separate function, its logic can be directly placed (or "inlined") where it's called.

Non-Optimized Approach:

solidityCopy codecontract Example {
    uint256 public value;

    function setValue(uint256 _value) public {
        _internalSet(_value);
    }

    internal function _internalSet(uint256 _newValue) {
        value = _newValue;
    }
}

Optimized (Inlined) Approach:

solidityCopy codecontract Example {
    uint256 public value;

    function setValue(uint256 _value) public {
        value = _value;
    }
}

Step-by-Step Guide for Function Inlining:

  1. Review: Identify internal functions in your contract that are called only once.

  2. Inline the Logic: Replace the single call to the internal function with its logic.

  3. Test: After making the change, ensure that the contract's functionality remains consistent. This is vital, as inlining can sometimes alter behavior if not done carefully.


Benefits:

  1. Gas Efficiency: Eliminate the overhead associated with function calls, resulting in gas savings.

  2. Code Simplicity: Reducing the number of functions can simplify the code, making it easier to read and audit.

  3. Reduced Attack Surface: Fewer functions might lead to a reduced attack surface, as there's less code that can potentially be exploited.


Considerations:

  1. Reusability: If there's a chance the internal function might be used more in future versions or by other contracts inheriting from it, consider keeping it.

  2. Readability: Sometimes, even if an internal function is called only once, it may serve to make the contract more readable. In such cases, consider the trade-off between gas efficiency and clarity.


Conclusion: Inlining single-use internal functions can be an effective way to make smart contracts more gas-efficient. However, always weigh the benefits against the potential future needs of your contract and the clarity of your code.

Last updated