An introduction to how storage works in Ethereum
storedData
, which is stored in the contract’s storage. The public
visibility modifier allows anyone to access this variable. The contract also includes a public function called updateData
, which can be called by anyone to modify the value of storedData
in storage.
Any changes made to storedData
in storage will persist across multiple transactions and will be visible to anyone who reads the blockchain. Please note that storage is more expensive than other data locations, so it is important to use it judiciously to minimize gas costs.
tempData
and assign the input parameter newData
to it to update its value. The tempData
variable is then assigned to the storedData
variable to update its value in storage.
Unlike storage, data stored in memory is not persisted across transactions and is only accessible during the execution of the function. However, accessing and modifying data in memory is less expensive than doing so in storage, making it a more efficient option when dealing with temporary data. Additionally, any data stored in memory is not visible on the blockchain and cannot be read by external parties.
sumLessEfficient
function, the sum of the two input arguments a
and b
is first assigned to the temporary variable temp
before being assigned to the state variable result
. This additional step introduces an extra variable on the stack, which requires more gas for stack operations and consumes more gas overall.
In contrast, the sumMoreEfficient
function directly assigns the sum of the input arguments a
and b
to the state variable result. This eliminates the need for the temporary variable and reduces the stack usage, leading to lower gas consumption for stack operations and a more gas-efficient execution.
Although the difference in gas consumption between these two functions may not be significant for such a simple example, the principle of minimizing stack usage and optimizing code to reduce gas consumption is essential for developing efficient smart contracts. By avoiding unnecessary variables and operations, you can improve the gas efficiency of your functions and reduce the cost of executing them on the EVM.
a
and b
into the same storage slot, as they are both 1-byte variables and can fit into a single 32-byte storage slot. However, c
requires a separate storage slot due to its size (32 bytes).