러스트에서 인라인 정의

In Rust, a unit of (separate) compilation is a crate. If a function f is defined in a crate A, then all calls to f from within A can be inlined, as the compiler has full access to f . If, however, f is called from some downstream crate B, such calls can’t be inlined.

동일한 크레이트 내 함수는 컴파일러가 자동으로 인라인 여부를 결정하지만, 외부 크레이트의 함수는 그렇지 않다. 오직 함수의 시그니처만 열려있고 함수 내부는 여전히 비공개 상태이기 때문이다. 이를 위해서 나온 개념이 #[inline] 인 것이다.

  • Cross-crate inlining을 위해 나온 #[inline]

Thrid, when building an application, apply #[inline] reactively when profiling shows that a particular small function is a bottleneck. Consider using lto = true for releases. It might make sense to proactively #[inline] trivial public functions. Fourth, when building libraries, proactively add #[inline] to small non-generic functions.

프로파일링 도중에 몇몇 작은 함수들이 병목현상을 일으킨다면 #[inline] 을 붙이자. 제너릭 함수가 아닌 작은 함수들에 인라인을 붙이자. private 함수들에 굳이 인라인을 붙일 필요는 없다. 하지만 public 인라인 함수가 private 함수를 호출할 땐 private 함수까지 인라인을 붙여야 한다.


  • #[inline] guides the compiler to not make a heuristic decision whether or not to inline the function body into the caller. The compiler is still free to disregard this attribute entirely or at specific call-sites if it so chooses for whatever reason since inlining does not change the program's behaviour in any observable way.
  • const is part of the function's signature and guarantees that the function can be (but not necessarily is) evaluated at compile time. The compiler may choose to evaluate the function body at compile time if it can, yet it is free to move that to runtime. The reason to make a function const is that the possibility to be evaluated in a const-context is part of the function's signature, guaranteeing this property in a semver-stable way. That is, a function that can be called in a const-context should not suddenly lose this property without a semver-bump.