Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compiler doesn't optimise away memory allocation. #94109

Closed
norpadon opened this issue Feb 18, 2022 · 1 comment
Closed

Compiler doesn't optimise away memory allocation. #94109

norpadon opened this issue Feb 18, 2022 · 1 comment

Comments

@norpadon
Copy link

norpadon commented Feb 18, 2022

In the following code rustc nightly (but not 1.58!) can successfully remove memory allocation and directly inline the answer: https://godbolt.org/z/s8G33jWEv

pub struct BBox {
    top: i32,
    left: i32,
    height: i32,
    width: i32
}

fn fiddle(bbox: &BBox) -> Box<BBox> {
    Box::new(BBox {
        top: bbox.top * 2,
        ..*bbox
    })
}

pub fn main() {
    let bbox = Box::new(BBox {
            top: 551,
            left: 100,
            height: 200,
            width: 180,
    });
    let bbox = fiddle(&bbox);
    let bbox_top = bbox.top;
    println!("{}", bbox_top)
}

But if I replace

let bbox_top = bbox.top;
println!("{}", bbox_top)

with

println!("{}", bbox.top)

it stops applying this optimisation: https://godbolt.org/z/oY8WrvfE7

Both clang and GCC can easily optimise equivalent C code:
https://godbolt.org/z/be9zPvYMj

@nikic
Copy link
Contributor

nikic commented Feb 18, 2022

Duplicate of #50519. This is a general problem with println!() captures, not really related to allocations.

@nikic nikic closed this as completed Feb 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants