Solidity Storage – Understanding Gas Cost to Read a Member of a Global Struct in Solidity

memorysoliditystoragestruct

Say I have a global state variable struct MyStruct that has multiple members/attributes/fields, what is the gas cost for reading a specific member? Is it equivalent to the gas cost of reading the entire struct or much less and proportionate to that member. So if a struct has 16 uint members, then is the gas cost for reading/loading just 1 of the 16 members from storage approximately 1/16 the gas cost of reading/SLOADing the entire struct?

Best Answer

The costs of reading a full struct from storage in a contract heavily depends on your struct.

You pay gas costs for every storage slot that you access. If your struct spans multiple storage slots and you read them all at once (by loading the whole struct) you will pay more gas than only loading a specific member of the struct.

But Solidity can fit multiple parameters into one slot. (see related question and Solidity docs). In this case reading all at once is cheaper since you only access one storage slot one time.

These struct storage optimizations of Solidity become more important when you update a struct (so storage writes) as writing multiple storage slots is significantly more expensive than writing a single storage slot.

Note: Repeatedly writing or reading the same storage slots became a lot cheaper with EIP-2929