存储与内存
数据位置
存储与内存 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web3 & DApp Development Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Data Location Matters
In Solidity, reference types must specify a data location. The three locations are storage, memory, and calldata.
Choosing the right one affects persistence, mutability, and most importantly gas cost.
Storage
Storage is the contract's permanent on-chain state. State variables live here, and writing to storage is the most expensive operation.
Data in storage persists between transactions.
<code>contract Bank {
uint256 public total; // lives in storage forever
function add(uint256 v) public {
total += v; // writes to storage (expensive)
}
}</code>Memory
Memory is a temporary scratchpad that exists only during a function call. It is much cheaper than storage and is cleared when the function returns.
Use memory for intermediate calculations and data you do not need to persist.
<code>function build() public pure returns (uint[] memory) {
uint[] memory temp = new uint[](3);
temp[0] = 1;
temp[1] = 2;
return temp; // discarded after call
}</code>Calldata
Calldata is a read-only, non-modifiable location holding function arguments for external calls. It is the cheapest option because nothing is copied.
Use it for function parameters you only need to read.
<code>function sum(uint[] calldata values) external pure returns (uint total) {
for (uint i = 0; i < values.length; i++) {
total += values[i];
}
}</code>Storage Pointer to State
Inside a function, a storage local variable is a pointer to existing state. Modifying it changes the contract's actual storage.
<code>struct User { uint balance; }
mapping(address => User) users;
function credit() public {
User storage u = users[msg.sender];
u.balance += 100; // updates real state
}</code>Memory Copy of State
If you instead load state into a memory variable, you get an independent copy. Changes to the copy do NOT update the contract's storage.
This is a common source of bugs for beginners.
<code>function noEffect() public view returns (uint) {
User memory u = users[msg.sender];
u.balance += 100; // only the copy changes
return u.balance; // storage is untouched
}</code>Gas Cost Comparison
The cost ranking, from cheapest to most expensive:
- calldata - read-only external args, no copy
- memory - temporary, copied into RAM
- storage - persistent on-chain, very costly to write
A fresh storage write (zero to non-zero) is one of the priciest EVM operations.
Prefer calldata for external
For external functions whose array or struct parameters are only read, use calldata instead of memory to avoid an unnecessary copy and save gas.
<code>// Cheaper: no copy is made
function process(bytes calldata data) external {
// read data directly
}</code>Where Defaults Apply
State variables are always storage. Function parameters and locals of reference type must declare a location explicitly. Value types and mapping members default to storage rules automatically.
Local mappings must always be storage - they cannot live in memory.
<code>// mapping locals must be storage
function f() public {
// mapping(...) memory m; // ERROR
}</code>Caching Storage Reads
A gas optimization: if you read the same storage variable multiple times, copy it into a memory local once. Each storage read (SLOAD) costs gas.
<code>function loop() public view returns (uint) {
uint cached = total; // one SLOAD
uint acc;
for (uint i = 0; i < 10; i++) {
acc += cached; // reads memory, cheap
}
return acc;
}</code>Returning Memory
Functions that build and return new arrays or structs use memory for the return value, since storage cannot be returned by value and calldata is input-only.
<code>function pair(uint a, uint b) public pure returns (uint[] memory) {
uint[] memory out = new uint[](2);
out[0] = a;
out[1] = b;
return out;
}</code>Quick Check
Test your understanding of data locations.
Recap
You learned how Solidity data locations work:
- storage - persistent, on-chain, most expensive to write
- memory - temporary scratchpad, copied, cleared after the call
- calldata - read-only external args, cheapest, no copy
Use storage references to mutate state, memory for temporary work, and calldata for read-only external inputs to save gas.
常见问题解答
「存储与内存」课时是免费的吗?
是的 — 「存储与内存」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。
「存储与内存」这节课中我会学到什么?
数据位置 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Web3 & DApp Development Fundamentals 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「存储与内存」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?
能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。