caching sload into mload
Last updated
Last updated
Both debts[user]
& deposits[user]
are storage variables, given we are looking to pass a value from a mapping that was declared and as a public variable.
A single SLOAD costs 2100 gas, and is unavoidable the first time.
The second instance, (line 5), we are reloading the SLOAD from cache and it will cost 100 gas.
Hence the repetitive use of debts[user] twice will cost us 2200 gas.
To combat that, you could always store the object in memory, and load it from there, which is much cheaper.
So what you could do is write from storage to memory once (SLOAD
+ MSTORE
= 2103 gas), then read the memory variable twice (MLOAD
+ MLOAD
) = 6 gas.
SLOAD
+ MSTORE
= 2103 gas
MLOAD
+ MLOAD
= 6 gas
Total = 2109 gas