In solidity, We have three types of locations to store the data

  • memory
  • storage
  • Stack

What is memory in Solidity?

Memory is like RAM used to store short-lived data that spans around function calls.

Variables declared in function calls, store in memory after function call execution starts and memory is removed once function call execution stops.

There is no limit on the amount of memory storage as long as the blockchain node is available memory. It contains a byte array that can store up to 32 bytes of data.

Function arguments of a function calls are stored in memory

What is Storage in solidity?

Storage is like database data stored in a blockchain node file system. It is persistent and has access to multiple executions of the same contract.

the storage contains key and value pairs, each key and value pair stores 32 bytes of data.

Global variables declared in the global scope of the contract are stored here And Also, Reference type local variables such as Struct, Array, and mapping type are stored in memory by default.

What is a stack in Solidity?

Stack is a storage mechanism and one of the components of Ethereum Virtual Machine(EVM).

Value types such as Int or UInt types declared in a function are stored in the stack.

It stores a minimal amount of variable data and it cost gas.

Here is an example of usage

pragma solidity ^0.4.17;

// Creating a contract contract helloGeeks { // Initialising array numbers string[] public names;

// Function to insert values // in the array numbers function addNames() public { names.push(“john”); names.push(“Eric”);

//Creating a new instance
st[] storage myArray = numbers;
 
// Adding value to the
// first index of the new Instance
myArray[0] = 0;

} }

Difference between Memory and Storage and Stack in Solidity?

Storage Memory Stack
Permanent Storage temporary temporary
It contains keys and values like a hashtable Byte Array Byte Array
Uses state variables Local variables defined in function calls Local values of value types are stored
Contract state variable memory variables stack variables
Expensive gas operation Does not cost gas and inexpensive operation Inexpensive gas operation
keyword in solidity keyword in solidity Keyword in solidity

Important Notes:

State or global variables of a contract are stored in Contract storage Arguments to a function are stored in memory. Local variables of reference types are stored in storage, If you store reference types in memory, They must be compile-time fixed in size. Local variables value types are stored in the stack.