What is the memory keyword in Solidity?
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.
How to use memory and storage
Output
The memory_working function returns array numbers=[1, 2, 3, 4, 5].
The storage_working function returns array numbers=[0, 2, 3, 4, 5].
Explanation
Line 4: We create a contract
HelloWorld.Line 6: We allocate a uint array
numbers.Line 9: In
memory_workingfunction, we create a uint arrayAusing thememorykeyword and allocated it to thenumbersarray.Line 15: In
storage_workingfunction, we create a uint arrayBusing thestoragekeyword. This will pointBto the original array and any changes inBwill change the arraynumbers.
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