1

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?

2 Answers 2

1

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

-3

Reading data from Blockchain does not cost any gas.

4
  • 1
    It can if you submit a valid transaction to the network, even if you're not modifying state, you have services like Etherscan who run their own archive nodes which allow you to read contract state for free, but technically it's still possible to execute a view call directly on chain, so my question is in this context.
    – MShakeG
    Feb 13, 2022 at 5:05
  • @MShakeG the op says nothing about sending transactions
    – scibuff
    Feb 21, 2022 at 0:26
  • I think it's implied since it's a given that gas is only charged if a transaction is executed on the network.
    – MShakeG
    Feb 21, 2022 at 3:57
  • Well, the OP should ask that then. If the question is posed what "the gas cost to read" anything from a blockchain is ... the asnwer is simple "nothing". I'm not gonna asssume that OP is talking about txs unless he states that in his question ... otherwise, he might as well be talking about unicorns; so yeah, this is pretty much the first time I get downvoted for answering a question correctly ...
    – scibuff
    Feb 21, 2022 at 8:22

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.