Data - Storage vs Memory
Unexpected error with integration github-files: Integration is not installed on this space
Data Locations
The EVM can access and store information in six places:
Stack
Memory
Temporary variables that can be modified
Storage
Permanent variables that can be modified
Calldata
Temporary variables that can't be modified
Code
Logs
Data locations can only be specified for types:
Array
Strings
Struct
Mapping
Calldata
The variable only exists temporarily and can't be modified
Similar to memory, but use
calldatainstead ofmemoryif you don't plan on changing the variablecalldatavariable values can't be reassigned
Storage vs Memory
In Solidity, there are two locations where you can store variables — in storageand in memory.
storagerefers to variables stored permanently on the blockchain.memoryvariables are temporary, and are erased between external function calls to your contract. Think of it like your computer's hard disk vs RAM.
Usually, these keywords aren't needed because Solidity handles them by default. State variables (variables declared outside of functions) are by default storage and written permanently to the blockchain, while variables declared inside functions are memory and will disappear when the function call ends.
However, there are times when you do need to use these keywords, namely when dealing with structs and arrays within functions:
The Solidity compiler will give warnings to let you know when you should be using one of these keywords.
Understand that there are cases where you'll need to explicitly declare
storageormemory.
Storage is Expensive
One of the more expensive operations in Solidity is using
storage— particularly writes.This is because every time you write or change a piece of data, it’s written permanently to the blockchain. Forever! Thousands of nodes across the world need to store that data on their hard drives, and this amount of data keeps growing over time as the blockchain grows. So there's a cost to doing that.
In order to keep costs down, you want to avoid writing data to storage except when absolutely necessary. Sometimes this involves seemingly inefficient programming logic — like rebuilding an array in
memoryevery time a function is called instead of simply saving that array in a variable for quick lookups.In most programming languages, looping over large data sets is expensive. But in Solidity, this is way cheaper than using
storageif it's in anexternal viewfunction, sinceviewfunctions don't cost your users any gas. (And gas costs your users real money!).
Declaring arrays in memory
You can use the
memorykeyword with arrays to create a new array inside a function without needing to write anything to storage. The array will only exist until the end of the function call, and this is a lot cheaper gas-wise than updating an array instorage— free if it's aviewfunction called externally.Here's how to declare an array in memory:
Example
Last updated