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 contract contract fellowCoders { // Initialising array coders int[] public coders; // Function to insert values // in the array coders function Numbers() public { coders.push(1); coders.push(2); //Creating a new instance int[] storage myArray = coders; // Adding value to the // first index of the new Instance myArray[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 contract contract fellowCoders { // Initialising array coders int[] public coders; // Function to insert // values in the array // coders function Numbers() public { coders.push(1); coders.push(2); //creating a new instance int[] memory myArray = coders; // Adding value to the first // index of the array myArray myArray[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.
RELATED TAGS
CONTRIBUTOR
View all Courses