Clippy lints / Performance
Clippy lint · Performance · checked with Clippy 0.1.99
clippy::iter_overeager_cloned: Checks for usage of _.cloned().<func>() where call to .cloned() can be postponed
What it meansChecks for usage of _.cloned().<func>() where call to .cloned() can be postponed. It is in the performance group and warns by default.
Does it matter?
It’s often inefficient to clone all elements of an iterator, when eventually, only some of them will be consumed.
Code that could be written to run faster. Warns by default.
How to fix it
Clippy can fix this one for you: run cargo clippy --fix (add --allow-dirty if you have uncommitted changes). Review the diff before you commit.
Flagged
vec.iter().cloned().take(10);
vec.iter().cloned().last();
Write this instead
vec.iter().take(10).cloned();
vec.iter().last().cloned();
Turn it off, or on
Allow it where it does not fit your code, as narrowly as you can:
On one item
#[allow(clippy::iter_overeager_cloned)]
fn my_function() { /* ... */ }Whole crate (Cargo.toml)
[lints.clippy]
iter_overeager_cloned = "allow"One run
cargo clippy -- -A clippy::iter-overeager-clonedThe [lints] table needs Rust 1.74 or newer. In a workspace, put it under [workspace.lints.clippy] and add [lints] workspace = true to each member.
Clippy's own documentation
What it does
Checks for usage of _.cloned().<func>() where call to .cloned() can be postponed.
Why is this bad?
It’s often inefficient to clone all elements of an iterator, when eventually, only some of them will be consumed.
Known Problems
This lint removes the side of effect of cloning items in the iterator.
A code that relies on that side-effect could fail.
Examples
vec.iter().cloned().take(10);
vec.iter().cloned().last();
Use instead:
vec.iter().take(10).cloned();
vec.iter().last().cloned();
From the Clippy lint list (0.1.99), part of the Rust project, MIT or Apache-2.0. Official entry.
Related lints
- large_enum_variantlarge size difference between variants
- expect_fun_callChecks for calls to .expect(&format!(...)), .expect(foo(..)), etc., and suggests to use unwrap_or_else instead
- extend_with_drainuse of `extend` instead of `append` for adding the full range of a second vector
- format_in_format_argsDetects format! within the arguments of another macro that does formatting such as format! itself, write! or println!
- large_const_arraysChecks for large const arrays that should be defined as static instead
- manual_cleartruncating to zero length
All 847 Clippy lints · Rust compiler errors · Cargo.toml checker
Up next
Related lintclippy::large_enum_variantlarge size difference between variantsRead it next →Did this answer your question?