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 | 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 |
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;}}
Line 4: We create a contract, fellowcoders
, to illustrate the storage
keyword.
Line 7: We Initialize an array, coders
.
Line 11: We create a Numbers
function 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.
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;}}
Line 4: We create a contract, fellowCoders
, to illustrate the memory
keyword.
Line 7: We initialize a coders
array.
Line 12: We create a function to insert values in the coders
array.
Line 18: We use the memory
keyword to create a new instance.
Line 22: We add value to the first index of the array.