Storage and Memory in Solidity

What is Storage and Memory in Solidity?

Understanding Storage and Memory in Solidity is one of the toughest things to do. Storage and Memory as the name suggests can be related to something which might be there in your computer right now. Memory is like the RAM you have in your system and Storage is the Hard Drive of your system, both play an integral role in the smooth functioning of your laptop or computer. Much like how RAM functions in your laptop, i.e by holding temporary memory and Storage like the Hard Drive holds memory for long term use. Smart Contracts written in Solidity can use up as much memory as they want, however, once the execution is completed the Memory is wiped off completely. This is not the case with Storage, unlike Memory which is wiped off after every execution, Storage is always stored safely even after the execution is completed. Each execution of the smart contract has access to the previous storage of the previous executions.

As we know there is a gas cost for every transaction on the Ethereum Virtual Machine (EVM). The gas cost for transacting something which is stored in the memory is significantly less as compared to that of something stored in the storage. As a Solidity developer, one of your main areas of focus is to reduce the gas cost that your smart contract eats up as much as you can without compromising on the quality of your code, concepts like memory and storage separate average developers from excellent developers. An example of trying to reduce gas cost during transactions is to do the maths of the transaction in the memory and to store the final value which is to be transacted in the storage thus heavily reducing the gas cost as the storage memory has to be accessed only once here instead of the multiple times it would have been accessed if the maths was being done on the storage itself.

State variables, local variables and arrays are stored in Storage by default, if you want an array to be in the memory instead of the storage creating it with the 'memory' keyword will only create another local variable instead of setting the original one to memory as well. Function arguments are stored in memory by default.

Let's take a look at a smart contract made up entirely in the storage.

pragma solidity ^0.8.5

// Creating a Contract
contract CodedamnStorage {
 // Initialising an array of numbers
 int [] public numbers;
 // Function to insert values in the Array
 function Numbers() public {
   numbers.push(1);
   numbers.push(2);
   // passing the array into storage
   int [] storage numbersArray = numbers;
   // adding a number to the first position in the Array
   numbersArray[0] = 0;
 }
}

If you have any questions, you can find me on my Twitter and LinkedIn