---
eip: 5656
label: EIP-5656
title: MCOPY - Memory copying instruction
status: Final
type: Standards Track
category: Core
created: 2021-02-01
official: https://eips.ethereum.org/EIPS/eip-5656
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-5656.md
canonical: https://eips.huatuo.xyz/zh/eip-5656/
lang: zh
tldr: 新增 MCOPY 操作码（0x5E），这是一种廉价的原生方式来复制一块 EVM 内存，取代缓慢的 MLOAD/MSTORE 循环和 identity 预编译调用。
tags: [evm, opcode, memory, gas, cancun]
---

# EIP-5656: MCOPY - Memory copying instruction

> An efficient EVM instruction for copying memory areas

**TL;DR:** 新增 MCOPY 操作码（0x5E），这是一种廉价的原生方式来复制一块 EVM 内存，取代缓慢的 MLOAD/MSTORE 循环和 identity 预编译调用。

## 它解决什么问题？

在内存中复制字节是编译器不断在做的事：构建 ABI 编码数据、切片 `bytes`、复制结构体和数组。在这项 EIP 之前，EVM 没有对应的指令，所以代码有两种选择：

- 用 `MLOAD` / `MSTORE` 循环处理 32 字节的字，为每个字付费，再加上循环开销，并对末尾不足一个字的部分做麻烦的掩码处理。
- 调用 **identity 预编译**（地址 `0x04`），让它把输入复制到输出。这样可行，但要付出 `CALL` 的开销，而在 gas 重新定价之后，这变得很昂贵。

规范自己的例子：复制 256 字节，用展开的 `MLOAD`/`MSTORE` 至少需要 96 gas，通过 identity 预编译（[EIP-2929](/eip-2929/) 之后）至少需要 157 gas，而用 `MCOPY` 只需 **27 gas**。

## 它如何运作

操作码 `0x5E` 上的新指令 `MCOPY` 从栈中取三项，不返回任何值：

| 栈位置 | 值 |
| --- | --- |
| 栈顶 | `dst` – 目标偏移量 |
| 栈顶 - 1 | `src` – 源偏移量 |
| 栈顶 - 2 | `length` – 字节数 |

参数顺序与 `CALLDATACOPY` 和 `RETURNDATACOPY` 一致。

- 它把 `length` 字节从 `src` 复制到 `dst`，**就像经过一个中间缓冲区一样**，因此重叠的区域也能被正确处理（类似 C 的 `memmove`，而不是 `memcpy`）。
- 如果 `length > 0` 且任一范围超出当前内存大小，则内存会被扩展，并收取通常的扩展成本。
- gas 遵循其他复制类操作码：

```
words  = (length + 31) // 32
gas    = 3 + 3 * words + memory_expansion_cost
```

所以，在已经分配的内存中复制 32 字节需要 6 gas。

专用的操作码也有助于静态分析器：与 `CALL` 不同，已知 `MCOPY` 只会触及内存。

## 示例代码

在内联汇编中使用 `mcopy`（Solidity 0.8.24+，EVM 版本为 `cancun` 或更高）：

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

library MemCopy {
    /// Returns a copy of `data[start : start + len]`.
    function slice(bytes memory data, uint256 start, uint256 len)
        internal pure returns (bytes memory out)
    {
        require(start + len <= data.length, "out of range");
        out = new bytes(len);
        assembly {
            // skip the 32-byte length prefix on both arrays
            mcopy(add(out, 32), add(add(data, 32), start), len)
        }
    }
}
```

规范的测试用例，重叠复制 `MCOPY dst=0 src=1 len=8`：

```
before: 0001020304050607 08...
after:  0102030405060708 08...   (gas used: 6)
```

## 需要注意

- **状态：Final。** `MCOPY` 在 Cancun/Deneb（"Dencun"）升级中上线主网，与 [EIP-1153](/eip-1153/) 瞬态存储、[EIP-4844](/eip-4844/) blob 和 [EIP-6780](/eip-6780/) 一同发布。
- 较新的 Solidity 和 Vyper 编译器在面向 Cancun 或更高版本时会自动生成 `MCOPY`；如果你部署到尚未采用它的链上，请设置较旧的 EVM 版本，否则代码会遇到无效操作码。
- 客户端实现者必须避免分配真正的中间缓冲区，这可能成为 DoS 向量；采用原地 `memmove` 式的复制即可得到所需的语义。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-5656
