Why is storing in an array the first time in solidity costs higher than the other times? The other times it has a constant cost which is less than the first time.


(I'm sure this has come up before. If someone can find a previous answer then please duplicate... )

From the Yellow Paper, Appendix G, you'll see the following line:

Gsset - 20000 - Paid for an SSTORE operation when the storage value is set to non-zero from zero.

Meaning the first time you write a variable to storage, it's more expensive by 20,000 gas. Subsequent updates to the variable are cheaper.


As JBrouwer has pointed out in the comments, for structs arrays you also need to store the length, so you're writing to two initially-zeroed storage slots rather than one, equating to 40,000 extra gas.

| improve this answer | |
  • If you store an array you also have to store in the length slot (which is initially set to zero) and the value you want to store - this is hence at least 40k gas. – JBrouwer Nov 11 '19 at 12:25
  • Ah, yeah, good point :-) If you add it as an answer I'll definitely upvote. – Richard Horrocks Nov 11 '19 at 12:28
  • Include it in your answer =) You hence write to 2 slots not 1. – JBrouwer Nov 11 '19 at 13:13
  • Thanks, done :-) – Richard Horrocks Nov 11 '19 at 13:32
  • "For structs you also need to store the length" - I assume you mean array here instead of struct? Because struct x = {uint a}; can be stored in a single slot (like x someStructStorageValue) – JBrouwer Nov 12 '19 at 16:39

This is not unique to arrays, but to any state-variable in your contract.

Changing from zero to non-zero costs more gas than changing from non-zero to non-zero.

| improve this answer | |
  • Thank you didn't know it – Haya Raed Nov 11 '19 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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