Storage vs. memory in Solidity
Overview
memory is a keyword used to store data for the execution of a contract. It holds functions argument data and is wiped after execution.
storage can be seen as the default solidity data storage. It holds data persistently and consumes more gas.
Storage vs memory
storage | memory |
Stores data in between function calls | Stores data temporarily |
The data previously placed on the storage area is accessible to each execution of the smart contract | Memory is wiped completely once code is executed |
Consumes more gas | Has less gas consumption, and better for intermediate calculations |
Holds array, state and local variables of struct | Holds Functions argument |
Example of storage
pragma solidity ^0.5.12;// Creating a contractcontract fellowCoders{// Initialising array codersint[] public coders;// Function to insert values// in the array codersfunction Numbers() public{coders.push(1);coders.push(2);//Creating a new instanceint[] storage myArray = coders;// Adding value to the// first index of the new InstancemyArray[0] = 0;}}
Explanation
-
Line 4: We create a contract,
fellowcoders, to illustrate thestoragekeyword. -
Line 7: We Initialize an array,
coders. -
Line 11: We create a
Numbersfunction to insert values in the array coders. -
Line 17: We create a new instance
myArray. -
Line 21: We add a value to the first index of the new instance.
Example of memory
pragma solidity ^0.5.12;// Creating a contractcontract fellowCoders{// Initialising array codersint[] public coders;// Function to insert// values in the array// codersfunction Numbers() public{coders.push(1);coders.push(2);//creating a new instanceint[] memory myArray = coders;// Adding value to the first// index of the array myArraymyArray[0] = 0;}}
Explanation
-
Line 4: We create a contract,
fellowCoders, to illustrate thememorykeyword. -
Line 7: We initialize a
codersarray. -
Line 12: We create a function to insert values in the
codersarray. -
Line 18: We use the
memorykeyword to create a new instance. -
Line 22: We add value to the first index of the array.