To better understand the memory
keyword, we first need to understand how Ethereum stores data for smart contracts execution.
Data/variables can be stored in:
The syntax to declare memory variables is as follows:
pragma solidity ^0.5.12;// declaring a smart contractcontract exampleContract {function updateAge() public pure returns (uint[] memory retArr){uint[] memory age; // declares an unsigned int array in memoryage[0] = 20;return age; // after the function returns, the "age" array will be deleted from memory}}
Memory
variables can only be declared inside functions. When it is declared outside of a function, it will give an error, as shown in the example below:
pragma solidity ^0.5.12;// declaring a smart contractcontract exampleContract {uint[] memory age; // this line would give error, as "memory" variables can only be declared in fucntionsfunction updateAge() public pure returns (uint[] memory retArr){age[0] = 20;return age; // after the function returns, the "age" array will be deleted from memory}}
Syntax to declare storage variables is as follows:
pragma solidity ^0.5.12;// declaring a smart contractcontract exampleContract {uint[] age; // this array is declared in storage instead of memoryfunction updateAge() public returns (uint[] memory retArr){age[0] = 20;return age; // after the function returns, the "age" array will remain in the storage}}
Memory variables have faster access times as compared to storage variables because to access/modify storage variables. We'll need to traverse the entire modified MPT (Merkle Patricia tree-where all users' data is stored), whereas the memory variables will be created in the memory/RAM of the Virtual Machine (where the code is running on Ethereum nodes), which is much faster than the traversal of the entire modified MPT, stored in the hard drive.