Skip to content

Large by-value Copy arguments to functions not converted to by-reference leading to performance loss #52274

@YaLTeR

Description

@YaLTeR

https://godbolt.org/g/YodFQR

I have a big Copy type:

#[derive(Clone, Copy)]
struct HugeCopyType {
    arr: [i64; 1024],
}

I'm passing it to a function by value, and the function does not modify the argument which means it should be equivalent to passing it by reference:

fn process(arg: HugeCopyType) {
    let sum = arg.arr.iter().sum::<i64>();
    println!("{}", sum);
}

I'm calling the function from a loop:

let hct = HugeCopyType {
    arr: [0; 1024],
};

for _ in 0..512 {
    process(hct);
}

I expected Rust to be smart about this and convert the argument to be passed by reference, however it seems like that is not the case and it ends up being memcpy'd over and over inside the loop (see godbolt link above).

Changing the argument to pass by reference manually gets rid of the memcpys.

Rust: 1.26.0 (stable) and also beta and nightly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions