A0A*_*A0A 3 arrays time-complexity rust
lenRust中原始数组的方法的运行时复杂性是什么?据我所知,它是恒定的Vector和String,但是这些类型的每一个保持其长的赛道,我无法找到这是否是数组的情况下,任何文档.
原始数组具有恒定长度,因此可以安全地假设在编译期间可以计算数组的大小(编译时常量)
鉴于:
let array = [1, 2, 3, 4, 5];
println!("Length: {}", array.len());
Run Code Online (Sandbox Code Playgroud)
调试版本给出:
callq alloc::slice::<impl [T]>::len
movq %rax, -16(%rbp)
movq core::fmt::num::<impl core::fmt::Display for usize>::fmt@GOTPCREL(%rip), %rsi
Run Code Online (Sandbox Code Playgroud)
调试构建似乎将责任委派len给切片的方法.
但是,正如预期的那样,发布版本会在编译期间计算一个常量,将其直接推入堆栈并使用它:
movq $5, (%rsp)
movq core::fmt::num::<impl core::fmt::Display for usize>::fmt@GOTPCREL(%rip), %rax
Run Code Online (Sandbox Code Playgroud)