没有影响;我检查了为两个变体生成的程序集,它是相同的。
我对比的两个版本:
“外部的”:
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
}
"local":
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()
或在其之外。
Edit:正如 Shepmaster 指出的那样,在这个程序中没有副作用,因此两种变体生成的程序集实际上与以下程序集相同:
fn main() {}
然而,两者的 MIR 输出也相同(并且与空白的输出不同)main()
),因此即使存在副作用,函数位置也不应该有任何差异。