Iterating an array by value keeps a second copy of it on the stack even though the original is dead
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 38/100
- Tipo de issue
- Error
- Claridad
- Bastante claro
- Estado de actividad
- Activo
- Stack tecnológico
- compilers, rust
- Área
- compilers, performance
Línea de trabajo
Start by reproducing the reported stack frames and memcpy calls with the linked Godbolt example, then trace how array by-value iteration is lowered through core::array::IntoIter and optimized by rustc and LLVM. Compare by_value with by_reference and drain_gen_block; done when the cause is identified and a compiler change eliminates the redundant array copy without changing iteration behavior.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Iterating a local array by value (for value in array) copies the whole array into core::array::IntoIter with a memcpy, and both copies stay in the stack frame, even though the original array is never used again.
Iterating by reference doesn't have the copy.
Example (reduced by LLM from a real project for demo purposes):
#![feature(gen_blocks)]
use std::hint::black_box;
const N: usize = 128;
unsafe extern "Rust" {
safe fn consume(value: u64);
}
/// Fully visible to the optimizer, the address of `batch` doesn't escape
#[inline(always)]
fn fill(batch: &mut [u64; N]) {
let seed = black_box(1u64);
for (offset, value) in (0u64..).zip(batch.iter_mut()) {
*value = seed.wrapping_mul(offset);
}
}
/// Iterating the array by value: the array is copied into `array::IntoIter`, the original is dead
/// afterwards, yet both copies stay on the stack
#[unsafe(no_mangle)]
pub fn by_value() {
let mut batch = [0u64; N];
fill(&mut batch);
for value in batch {
consume(value);
}
}
/// The same with iteration by reference, only one array on the stack
#[unsafe(no_mangle)]
pub fn by_reference() {
let mut batch = [0u64; N];
fill(&mut batch);
for &value in &batch {
consume(value);
}
}
/// In a `gen` block the iterator must live in the coroutine state, and the array is still built on
/// the stack of the resume function first
#[unsafe(no_mangle)]
pub fn gen_block() -> impl Iterator<Item = u64> {
gen {
let mut batch = [0u64; N];
fill(&mut batch);
for value in batch {
yield value;
}
}
}
#[unsafe(no_mangle)]
pub fn drain_gen_block() {
for value in gen_block() {
consume(black_box(value));
}
}
https://rust.godbolt.org/z/3rY7qcY79
On x86-64:
| function | frame (sub rsp) |
memcpy calls |
|---|---|---|
by_value |
2072 B | 1 (1024 bytes, right after fill) |
by_reference |
1032 B | 0 |
drain_gen_block |
2080 B | 1 |
I expected by_value to only need one array since batch is dead after it is moved (copied) into the iterator, so the iterator can use its storage, and the frame should be about the size of by_reference.
LLVM apparently has stack-move optimization in MemCpyOpt (https://reviews.llvm.org/D153453), but it doesn't kick in here.
While workarounds for this are possible, neither of them look as pretty as gen {} block.
Possibly related issues found by LLM
- #87949 (
array::IntoIterdoesn't get optimized as well asvec::IntoIter, closed) - #86912 (
array::mapstack usage) - #84513 (the "copying large arrays" footgun listed as an open item of edition-dependent
IntoIteratorfor arrays) - #64301 (too many
memcpys) - #42763 (
selfmoved with a memmove into an inlinedinto_iter()) - #52274 (large by-value
Copyarguments copied) - #99504 (callee futures built in a stack temporary and then copied into the caller's state)
- #161506, #161568 (separate stack slots for call results due to MIR passes or MemCpyOpt)
Meta
rustc 1.102.0-nightly (65ce8611f 2026-11-18)
binary: rustc
commit-hash: 65ce8611fed3142053320be6996ef00e9992671f
commit-date: 2026-11-18
host: x86_64-unknown-linux-gnu
release: 1.102.0-nightly
LLVM version: 23.1.6
- Lenguaje dominante
- Rust
- Estrellas
- 123k
- Forks
- 16.6k
- Merge medio
- 2 d 17 h
- PR fusionados (30 d)
- 532
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de rust-lang/rust
-
strictly_dominates missing a `=`AbiertoC-bug needs-triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
rust-lang/rust#166722 · 1 reacción ·
Los mantenedores suelen responder en 1 día
-
A-attributes relnotes relnotes-needs-review relnotes-tracking-issue T-compiler T-lang
Dificultad 1/5 Menos de una hora Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
A-run-make C-bug T-bootstrap
Dificultad 2/5 1-3 horas Aptitud para principiantes 65/100
Los mantenedores suelen responder en 1 día
-
Tracking issue for release notes of #161531: Remove `T: Send + Sync` bound from `Arc::downcast`Abiertorelnotes relnotes-tracking-issue T-libs
Dificultad 1/5 Menos de una hora Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
A-str A-Unicode relnotes relnotes-tracking-issue T-libs
Dificultad 1/5 Menos de una hora Aptitud para principiantes 70/100
Los mantenedores suelen responder en 1 día
Todos los issues de rust-lang/rust
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
tamatebako/tebako#1155 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 79/100
swc-project/swc-next-issues#1148 ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 75/100
registrystack/registry-stack#2828 ·
Los mantenedores suelen responder en 1 día
-
agent:triaged arch-audit bug priority:p1
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
SocketDev/socket-patch#2364 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
bug P2
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
Los mantenedores suelen responder en 1 día