Say I have a complex(list
, mapping
or struct
) global/contract variable. What is the most gas efficient way to update that variable in a function that changes the value of one or more indexes, values or members in the case of the variable being a list
, mapping
or struct
respectively.
The first option I can think of would be to directly write the value/s to state, but I think this would be the most gas intensive as for every direct update you have one read and one write operation.
The second option would be to read that variable into a local state variable, perform updates on that local variable, then assign the global variable to that local variable. This initially seems to be more gas efficient than option 1, but this would only be true if the gas cost of assignment is fixed, for example if the contract variable is a list
then gas cost to write the local list
to the contract list
is fixed regardless of the length, so the gas cost of assigning a local list
to a contract list
of length 1 is equal to the gas cost if the list
was of length 1000, and similarly for other complex types i.e. mapping
and struct
.