Solidity – Why Local Variables are Allocated to Storage Instead of Memory

contract-developmentevmsolidity

Local variables (i.e. variables declared inside functions) are held in persistent storage by default instead of non-persistent memory (source).

The value of a local variable can not persist in between function invocations, so in my mind it makes more sense to have local variables stored in memory during the execution of a function call. Could someone explain the purpose of this decision?

Best Answer

It seems to be related to the data type that you're using. As TripleSpeeder noted, only complex data types (arrays and structs) default to storage inside functions, while all others default to memory.

Inside this StackExchange question is a description of the difference between memory and storage. To paraphrase one of the answers:

Storage is a key/value store where keys and values are both 32 bytes. Memory is a byte-array. Memory starts off zero-size, but can be expanded in 32-byte chunks by simply accessing or storing memory at indices greater than its current size.

A consequence of this design difference is that storage is dynamic and memory is not. Because arrays and structs are complex and could be of variable length, they are defaulted to storage, which has this key:value behavior. Simpler variables like bool, uint, et cetera are not variable in length, and are therefore defaulted to memory, which is cheaper than storage. So, think of the design choice as a compromise between flexibility and cost.

It is possible to create memory arrays, but once created they cannot be resized (check out the Allocating Memory Arrays section).

Related Topic