ETHEREUM SMART CONTRACT DEVELOPMENT

Solidity Fundamentals

Data Location and Assignment Behaviors

Ferdi Kurt
Coinmonks
Published in
2 min readDec 24, 2020

--

All reference type has an additional annotation, the data location, about where it is stored. There are three possible options: memory , storage,and calldata.

storage: The location type where the state variables are stored on blockchain which means types that has storage location are persistent.

memory: Variables are in memory and they exists during the function call which means variables that got this location are temporary and after function execution finished, they won’t exist.

calldata: Non-modifiable, non-persistent data location where function arguments are stored, behaves mostly like memory data location and only available for external functions. More on function types (external, public, internal, private) later.

An assignment or type conversion that changes the data location will always results in an automatic copy operation, while assignments inside the same data location only copy in some cases for storage types.

The data set location is important not only for the persistence of data but also for semantics of assignment. Let’s look at each behavior;

  • Assignments between storage and memory (or from calldata) always create an independent copy.
  • Assignments from memory to memory only create references. As a result changes to one memory variable are also visible in all other memory variables that refer to the same data.
  • Assignments from storage to a localstorage variable also only assign a reference.
  • All other assignments to storage always creates independent copies.

I wanted to remind you couple of things about usage of structs. Let’s see below example;

Last notes on reference types. If we are dealing with reference types, we should be very careful due to below reasons.

  • Reference types don’t necessarily fit into 32bytes — 256 bits.
  • Amount of gas consumed during execution depends on data location. Creating independent copies from reference types are expensive thus it is recommended that mostly inside functions we should choose working with memory data location.
  • We must be careful in scenario when two or more different variables point same data location since any change in one variable will impact the others.

Lastly, let’s look at a little bit complicated but very valuable usage of structs, mapping and enums in an escrow like contract.

Next, we will be working on control structures. Thanks for reading.

Feel free to ask any question.

Stay safe, do good work, and keep in touch!

Ferdi Kurt

--

--