2

In the solidity doc, it says it "might be" beneficial to pack multiple reduced-sized state variables into one storage slot. And it gives an exception case that when the packed variables in a single slot are not read or written at the same time, it actually costs more gas because "the storage slot has to be read first and then combined with the new value".

My question is since we almost never read or write packed variables in a single slot at the same time, why do we still try packing these variables together? The alternative is just to use a single slot for each reduced-size variable, in which case EVM will need to run additional operations to reduce 32 bytes data to its desired size. Given that both single-slot storage and multi-slot storage have disadvantages in extra gas costs, how do we know for sure which way of storage costs less gas? Thank you!

See quotes from solidity doc.'s warning:

When using elements that are smaller than 32 bytes, your contract’s gas usage may be higher. This is because the EVM operates on 32 bytes at a time. Therefore, if the element is smaller than that, the EVM must use more operations in order to reduce the size of the element from 32 bytes to the desired size.

It might be beneficial to use reduced-size types if you are dealing with storage values because the compiler will pack multiple elements into one storage slot, and thus, combine multiple reads or writes into a single operation. If you are not reading or writing all the values in a slot at the same time, this can have the opposite effect, though: When one value is written to a multi-value storage slot, the storage slot has to be read first and then combined with the new value such that other data in the same slot is not destroyed...

https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#storage-inplace-encoding

1 Answer 1

0

Deciding whether to pack variables or use single-slot storage for each reduced-size variable depends on the specific use case and the frequency of reads/writes for each variable. Ultimately, the best approach is to test and compare the gas costs for both options to determine which is more efficient in each specific scenario.

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.