0

In one function, I was forced to declare a variable with the memory type storage (since there is mapping inside the struct). Is it much more expensive than memory? And how justified is it if I will use this local variable only for reading? I compared the cost of a call in Remix with the memory type and the storage type.

P.S A call with storage memory turned out to be even slightly cheaper. This is because there is no new copy being created for memory, right?

enter image description here

1 Answer 1

0

Yes, you're right. If the local variable has the storage memory identifier then it will be assigned a reference from the storage state variable. On the other hand, if the variable was memory then it would create a new copy. So it will be cheaper to use storage type as it would only read two words from memory (I hope it is so, but your presentation of the code is horrible, please, next time provide us with a code snippet instead of some peek-in-hole picture), while the memory will read all the struct element which is more than two words I believe (more code next time!).

Take a note though that an mload opcode uses 3 gas units while an sload uses 200, so if you were to read multiple times from the struct element that you would end up using more gas in the memory case.

You can read more about memory assignments in the official docs of Solidity language.

1
  • 1
    Thank you for the detailed explanation and sorry for the peek-in-hole picture.
    – Nikita Rov
    Commented Jul 19, 2021 at 12:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.