Solidity Calldata vs Memory
Calldata is a read-only area that holds the arguments of an external function call. It costs less to read than copying those arguments into memory.
A calldata array can be summed
The function reads the array straight from calldata. No copy into memory is made.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract SumCalldata {
function sum(uint256[] calldata xs) external pure returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < xs.length; i++) {
total += xs[i];
}
return total;
}
}A calldata string can be measured
The function reads the string from calldata and returns its length. The string itself is never changed.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract StringCalldata {
function lengthOf(string calldata s) external pure returns (uint256) {
return bytes(s).length;
}
}Calldata cannot be changed
Writing to a calldata value fails to compile. The error below is the real compiler message.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract BadEdit {
function edit(uint256[] calldata xs) external pure {
xs[0] = 99;
}
}Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract ScoreList {
function summarize(uint256[] calldata xs) external pure returns (uint256 total, uint256 first, uint256 count) {
total = 0;
for (uint256 i = 0; i < xs.length; i++) {
total += xs[i];
}
first = xs[0];
count = xs.length;
}
}Key points
- Calldata: the read-only arguments handed to an external function.
- Memory: a changeable copy that costs more to build.
- Arrays and strings: external parameters of these types can use calldata.
- Read-only rule: code can read calldata values but cannot change them.
- Use calldata to pass large inputs that a function only needs to read.
In this example, one function takes a calldata array and returns its total, its first value, and its length. All three answers come from reading calldata alone.
Note
calldata is only available on external function parameters.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
When should a parameter use calldata?