# Gas Saving Technique 20: Storage vs Memory read optimizations

{% hint style="info" %}
[**Book an audit with Zokyo**](https://www.zokyo.io/)
{% endhint %}

#### Introduction

In the realm of smart contracts, efficient gas usage is of the essence. An impactful method for economizing gas consumption is minimizing unnecessary storage reads, as reading from storage (using `SLOAD`) is considerably costly in terms of gas. This tutorial aims to shed light on how to optimize storage reads to save gas.

#### Impact & Details

**Why Optimize Storage Reads?**

* **Cost Efficiency**: `SLOAD` operations are expensive, costing around 100 gas per operation, while `MLOAD` and `MSTORE` operations are considerably cheaper at approximately 3 gas each. Therefore, reducing `SLOAD` operations can lead to significant gas savings.
* **Optimized Performance**: By caching storage variables in memory, you can enhance the contract's performance, making it more efficient and responsive.

#### Example: Storage Read Optimization

**Before Optimization:**

```solidity
solidityCopy codepragma solidity ^0.8.0;

contract StorageOptimization {
    uint256[] public numbers;

    function calculateSum() public view returns (uint256) {
        uint256 sum = 0;
        for (uint256 i = 0; i < numbers.length; i++) {
            sum += numbers[i];  // Multiple SLOAD operations due to repeated storage reads
        }
        return sum;
    }
}
```

**After Optimization:**

```solidity
solidityCopy codepragma solidity ^0.8.0;

contract StorageOptimization {
    uint256[] public numbers;

    function calculateSum() public view returns (uint256) {
        uint256 sum = 0;
        uint256 length = numbers.length;  // Caching the length in memory
        for (uint256 i = 0; i < length; i++) {
            sum += numbers[i];  // Reduces the number of SLOAD operations
        }
        return sum;
    }
}
```

#### Recommended Mitigation Steps

1. **Identify Repeated Storage Reads**: Look for any storage variables being read multiple times within a function, especially within loops.
2. **Cache in Memory**: Cache storage variables in memory if they are being read multiple times within the same function or scope, particularly in loops.
3. **Test for Gas Savings**: After making adjustments, test the function to verify that it is not only still working as expected but also using less gas.

#### Conclusion

Minimizing storage reads by caching storage variables in memory significantly aids in reducing gas consumption, leading to more efficient and cost-effective smart contracts. Adopt this practice consistently across your smart contracts to ensure you're developing gas-optimized, high-performance decentralized applications. Always remember to test your contracts thoroughly after implementing these optimizations to ensure they work as intended.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zokyo-auditing-tutorials.gitbook.io/zokyo-gas-savings/tutorials/gas-saving-technique-20-storage-vs-memory-read-optimizations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
