SolidityIn

Storage, memory and calldata

Lesson 6 of 40 · Functions

Reference types such as arrays, structs and strings need a data location. storage points at permanent chain state, memory is a temporary copy that disappears when the call ends, and calldata is read-only input sent with the transaction.

Use calldata for external function parameters that you only read, since it avoids a copy and saves gas. Use memory when you need to change a local copy or build a new array.

Assigning between locations behaves differently. Copying from storage into a memory variable makes an independent copy, so changes to it are lost. A storage variable inside a function is a pointer to the original, so changes to it are saved. Mixing these up is one of the most common beginner bugs.

Reading and writing storage are the most expensive things a contract does, while memory is cheap. When a function reads the same storage variable many times, copy it into a local variable first.

Local variables of value types, such as uint256, have no data location at all. They live on the stack for the length of the call.

contract Locations {
    struct Item { string label; uint256 qty; }
    Item[] public items;

    function add(string calldata label, uint256 qty) external {
        items.push(Item(label, qty));
    }
    function sum(uint256[] calldata xs) external pure returns (uint256 t) {
        for (uint256 i = 0; i < xs.length; i++) t += xs[i];
    }
    function brokenBump(uint256 i) external view returns (uint256) {
        Item memory it = items[i];     // a copy
        it.qty += 1;                    // lost when the call ends
        return it.qty;
    }
    function bump(uint256 i) external {
        Item storage it = items[i];    // a pointer
        it.qty += 1;                    // saved on chain
    }
}

Try it yourself

Use add, then bump, and read items(0) to see qty change. Then change storage to memory in bump and compile: the compiler warns that the function can be restricted to view, because nothing is saved any more.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: What happens to changes made to a memory copy of a struct?