When we use the opcode sload, which is used to read a value from storage or a state variable, it consumes more gas. This is because the EVM reduces gas costs when data is written to or read from storage. If we examine the for loops closely, we can see that each iteration reads data from storage, which results in a high gas cost for executing those loops. To optimize this, it is a good practice to store that value in a memory type variable. By doing this, the length of the mapping is only read once, which helps to save gas.
When we use the opcode
sload
, which is used to read a value from storage or a state variable, it consumes more gas. This is because the EVM reduces gas costs when data is written to or read from storage. If we examine thefor
loops closely, we can see that each iteration reads data from storage, which results in a high gas cost for executing those loops. To optimize this, it is a good practice to store that value in a memory type variable. By doing this, the length of the mapping is only read once, which helps to save gas.Thanks @noumanmhd