没有影响;我判断了为两个变体生成的程序集,它是相同的.
我比较了两个版本:
"外部":
fn main() {
let x = 2i64;
let y = 5i64;
let external_res = external_plus(x,y);
}
fn external_plus(x: i64, y: i64) -> i64 {
x + y
}
"本地":
fn main() {
fn local_plus(x: i64, y: i64) -> i64 {
x + y
}
let x = 2i64;
let y = 5i64;
let local_res = local_plus(x, y);
}
两者都会产生相同的asm结果(在今天的夜间发布模式):
.text
.file "rust_out.cgu-0.rs"
.section .text._ZN8rust_out4main17hb497928495d48c40E,"ax",@progbits
.p2align 4, 0x90
.type _ZN8rust_out4main17hb497928495d48c40E,@function
_ZN8rust_out4main17hb497928495d48c40E:
.cfi_startproc
retq
.Lfunc_end0:
.size _ZN8rust_out4main17hb497928495d48c40E, .Lfunc_end0-_ZN8rust_out4main17hb497928495d48c40E
.cfi_endproc
.section .text.main,"ax",@progbits
.globl main
.p2align 4, 0x90
.type main,@function
main:
.cfi_startproc
movq %rsi, %rax
movq %rdi, %rcx
leaq _ZN8rust_out4main17hb497928495d48c40E(%rip), %rdi
movq %rcx, %rsi
movq %rax, %rdx
jmp _ZN3std2rt10lang_start17h14cbded5fe3cd915E@PLT
.Lfunc_end1:
.size main, .Lfunc_end1-main
.cfi_endproc
.section ".note.GNU-stack","",@progbits
这意味着生成的二进制文件中会有零差异(不仅仅是性能方面的差异).
更重要的是,你是否使用函数都无关紧要;以下方法:
fn main() {
let x = 2i64;
let y = 5i64;
let res = x + y;
}
也会产生相同的组件.
底线是,通常情况下,函数都是内联的,不管您是在main()
中声明它们还是在main()
之外声明它们.
Edit:正如Shepmaster所指出的,在这个程序中没有副作用,因此两种变体生成的装配实际上与以下两种变体的装配相同:
fn main() {}
然而,两者的MIR输出也是相同的(与空白main()
的MIR输出不同),因此即使存在副作用,功能位置也不会有任何差异.