Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any performance disadvantage to putting everything in main?

In Rust, it appears you can basically put anything in main. Traits, implementation blocks, functions, static variables...

For instance, this compiles:

fn main() {
    trait Foo {
        fn foo();
    }

    impl Foo for f64 {
        fn foo() {}
    }

    struct MyStruct;

    enum RustIsCool {
        MyStruct,
    };

    fn bar() {
        trait Baz {
            fn baz();
        }

        impl Baz for f64 {
            fn baz() {}
        }
    }

    static x: f64 = 10.0;

    println!("This compiles!");
}

As you can see, you can even nest these things inside of other blocks.

Obviously, doing this is bad from a stylistic point of view; it's ugly, harder to refactor, and makes code reuse more difficult.

But I'm curious: is there any performance overhead in doing this? Or does the Rust Compiler optimize any differences away?

like image 493
hkk Avatar asked Mar 08 '23 02:03

hkk


1 Answers

Short answer: Nothing significant will be different.

If you look at the LLVM-IR for your code on playground and compare it with code where all of your definitions are outside of main(), you'll see that there are no differences (except due to naming) in "Debug" mode. In "Release" mode, there aren't any differences at all.

However, it is certainly possible that the location of your test code can affect code generation. But these are minor effects. There is nothing fundamental which would need to influence code generation (such as if the definition in main would have an implicit reference to main's variables).

Some reasons which could possibly affect code generation:

  • Since the definitions in main() cannot be used outside of main(), this could be a strong hint to inline function calls to those things and remove the original definition, if possible. This would, in general improve performance.
  • rustc generates slightly different LLVM-IR, so LLVM could in theory generate different code (butterfly effect)
  • ...
like image 113
Lukas Kalbertodt Avatar answered Mar 16 '23 00:03

Lukas Kalbertodt