Reputation: 41
Solidity has 3 difference memory storage: storage, memory and stack. After reading lots of articles online, I still can't understand the difference between memory and stack. My question would be:
Q1. What's the difference between memory and stack?
Q2. Suppose I have defined a local variable in function, how do I know that this variable is stored in memory or stack? (The variable is in memory only if the declaration of the variable goes with the "memory" keyword?)
Thanks, everyone.
Thanks for the reply from @Yilmaz . According to your answer, say we have a function written like this:
function test() public {
string memory str;
int i;
}
Are str
and i
both on "memory" and on "stack" simultaneously?
My third question is:
Q3. Why do only array, struct, and mapping types need to specify memory location?
Why Solidity doesn't allow me to write int memory i;
in above code?
Upvotes: 4
Views: 1849
Reputation: 49293
Storage is where the variables are permanently stored on the blockchain. If you want to manipulate the data in storage you copy it to the memory. Then, all memory code is executed on stack. Stack has a maximum depth of 1024 elements and supports the word size of 256 bits.
When you define the local variable it is stored in memory and then pushed to the stack for execution.
str
and i
both are not on "memory" and on "stack" simultaneously. You see the image, there is push
code that moves the variable from memory to stack. If EVM
was keeping both on the memory and stack instantaneously, it would not be cost efficient.for your 3rd question please refer this: In Ethereum Solidity, what is the purpose of the "memory" keyword?
I explained it with details
Upvotes: 6