Local Variables (Storage v Memory)
Only complex data types (arrays and structs) default to storage inside functions, while all others default to memory.
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. https://ethereum.stackexchange.com/questions/1232/difference-between-memory-and-storage
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 behaviour.
Simpler variables like bool, uint, etc 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).
For value types (booleans, integers, addresses ...) it's memory. For complex types (arrays, structs, maps) the default location depends on the context and can be overridden by memory
and storage
keywords.
Results
Compiling with the optimizer leads to the same bytecode and gas cost.
If the optimizer is not used, the compiler would produce more bytecode, and the gas cost would be higher.
Links
Last updated