What is the difference between `memory` and `storage` in Solidity?
Answer
Data location in Solidity determines where data is stored and its persistence: (1) Storage — persistent, on-blockchain storage. State variables are always in storage. Reading from storage costs gas (SLOAD: 100-2100 gas depending on cold/warm access); writing is expensive (SSTORE: 20,000 gas for new slot, 5,000 for update). Data persists between function calls and transactions; (2) Memory — temporary, in-memory storage during function execution only. Cleared after function returns. Much cheaper than storage for complex operations (arrays, structs). Required keyword when declaring reference types (arrays, structs, strings) in function parameters and local variables; (3) Calldata — special read-only data location for function arguments in external functions. Cheaper than memory for large data because it doesn't copy data. Example: function processArray(uint[] calldata data) external pure returns (uint) { ... }; (4) Stack — the EVM execution stack; Solidity manages this automatically for simple value types in local variables. Use the least expensive location for your use case: calldata > memory > storage in terms of gas efficiency.