Skip to content

Suggest zip + repeat_n instead of loop + clone #16291

@SpriteOvO

Description

@SpriteOvO

What it does

Using zip + repeat_n instead of loop + clone, we can reduce one unnecessary clone.

Advantage

  • Performance, we could reduce 1 time unnecessary clone cost.

Drawbacks

  • This requires changing the loop block to a .for_each() or introducing a .unwrap() call, even though it will never panic.
  • This requires the loop range has .len() method.

Example

fn set_something<T: Clone>(value: T) {
    for prop in props.iter() {
        prop.set(value.clone());
    }
}

This function will clone value props.len() times.

If we change the implementation to use zip + repeat_n, we could reduce it to clone value props.len() - 1 times.

fn set_something<T: Clone>(value: T) {
    props
        .iter()
        .zip(std::iter::repeat_n(value, props.len()))
        .for_each(|prop, value| prop.set(value));
}

Or

fn set_something<T: Clone>(value: T) {
    let mut value = std::iter::repeat_n(value, props.len());
    for prop in props.iter() {
        prop.set(value.next().unwrap());
    }
}

Comparison with existing lints

No response

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions