What is the purpose of "memory" keyword in Ethereum Solidity?

Overview

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:

  • Memory
  • Storage

Memory

  • We store data in memory temporarily. For instance, data stored in the computer's RAM wipe out when the computer is turned off or after the function returns.
  • We also store the function arguments and local variables in memory.
  • Memory has limited space available. Thus, all function's local variables are deleted after the function returns.
  • More local variables (stored in memory) are created when a function is called.

Syntax

The syntax to declare memory variables is as follows:

pragma solidity ^0.5.12;
// declaring a smart contract
contract exampleContract {
function updateAge() public pure returns (uint[] memory retArr)
{
uint[] memory age; // declares an unsigned int array in memory
age[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 contract
contract exampleContract {
uint[] memory age; // this line would give error, as "memory" variables can only be declared in fucntions
function updateAge() public pure returns (uint[] memory retArr)
{
age[0] = 20;
return age; // after the function returns, the "age" array will be deleted from memory
}
}

Storage

  • It stores data permanently, e.g., like a hard drive
  • We store the state variables in storage.
  • Storage has more space available. Thus it retains data even after the function has returned.
  • Storage variables can only be declared when the smart contract is being deployed.

Syntax

Syntax to declare storage variables is as follows:

pragma solidity ^0.5.12;
// declaring a smart contract
contract exampleContract {
uint[] age; // this array is declared in storage instead of memory
function updateAge() public returns (uint[] memory retArr)
{
age[0] = 20;
return age; // after the function returns, the "age" array will remain in the storage
}
}

Conclusion

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.