In Solidity, we use the memory
keyword to store the data temporarily during the execution of a smart contract.
When a variable is declared using the memory
keyword, it is stored in the memory area of the
It is easy to access memory and there is low cost involved. However, it is also volatile and has a limited capacity. That means the data stored in memory is not persistent and will be lost when the contract execution is finished. If we want data to persist, we will use the storage
keyword.
pragma solidity ^0.5.0;contract HelloWorld {uint[5] public numbers=[1, 2, 3, 4, 5];function memory_working() public view returns (uint[5] memory){uint[5] memory A = numbers;A[0] = 99;return numbers;}function storage_working() public returns (uint[5] memory){uint[5] storage B = numbers;B[0] = 0;return numbers;}}
The memory_working
function returns array numbers
=[1, 2, 3, 4, 5].
The storage_working
function returns array numbers
=[0, 2, 3, 4, 5].
Line 4: We create a contract HelloWorld
.
Line 6: We allocate a uint array numbers
.
Line 9: In memory_working
function, we create a uint array A
using the memory
keyword and allocated it to the numbers
array.
Line 15: In storage_working
function, we create a uint array B
using the storage
keyword. This will point B
to the original array and any changes in B
will change the array numbers
.
After the execution of the contract the array A
, which was allocated using memory
keyword will be wiped out, but the array B
will stay and can be accessed by future contracts.
Free Resources