Arc - zero cost abstraction - optimization
⚓ Rust 📅 2025-09-28 👤 surdeus 👁️ 7Hi,
I was playing with some code in rust, and was trying to see how much overhead coming from Arc, especially when it should be zero cost abstraction.
In first example, it is obvious that Arc is useless in this case, and I was checking if Rust will do Zero Cost Abstraction, however here what I’ve got in assembly:
||movq|$21, 16(%rax)|
||movq|$22, 24(%rax)|
||movq|%rax, (%rsp)|
||movq|$21, 56(%rsp)|
||leaq|64(%rsp), %rax|
||movq|$23, 64(%rsp)|
Obviously first two instructions are redundant here. While same thing without Arc work nicely.
Is there a way to setup compile time optimization for such scenarios?
use std::sync::Arc;
struct S {
    f1: u64,
    f2: u64,
}
fn main() {
    let s1 = S { f1: 5, f2: 6 };
    // print_s(&s1);
    // s1.f1 = 8;
    //   print_s(&s1);
    let s2 = S { f2: 12, ..s1 };
    print_s(&s2);
    let s3 = Arc::new(S { f1: 21, f2: 22 });
    let s4 = S { f2: 23, ..*s3 };
    print_s(&s4);
}
fn print_s(s: &S) {
    println!("S: {}, {}", s.f1, s.f2)
}
Output:
S: 5, 12
S: 21, 23
Errors:
   Compiling playground v0.0.1 (/playground)
    Finished `release` profile [optimized] target(s) in 0.60s
     Running `target/release/playground`
1 post - 1 participant
🏷️ Rust_feed