可声明为inline的小型函数:如何定义“极小”的判定标准?
Great question—this is one of those classic rules of thumb that feels frustratingly vague at first, because there’s no hard-and-fast line count rule. Let’s break down how to think about it:
First, the core point: It’s not just about lines of code
The goal of inline is to eliminate the overhead of a method call (stack frame setup, parameter passing, return jump). So a method is "tiny" when its execution time is significantly smaller than the cost of calling it. Raw line count is a rough proxy, but the complexity of the method matters far more.
Common practical guidelines
1-3 lines: Almost always fair game
This includes getters/setters (return this->value;), simple arithmetic (return a + b * c;), or trivial null checks. These methods have negligible execution time, so eliminating call overhead gives a clear performance benefit.5-10 lines: Use caution, depend on context
If the method is a hot path (called thousands/millions of times per second) and has no complex control flow (no loops, minimal conditionals), it might still make sense to mark it inline. For example, a small vector math helper that adds two 3D points: even if it’s 8 lines of simple assignments, inline could help. But if it has branches or tiny loops, the call overhead becomes less significant compared to the method’s actual work.10+ lines: Rarely worth manual inlining
Beyond this point, the method’s execution time is almost certainly larger than the call overhead. Inlining here would just bloat your binary size, which can hurt cache performance (since more code means less fits in CPU cache). Modern compilers will almost always reject manualinlinehints for methods this size anyway.
Remember: Compilers are smarter than you think
Most modern compilers (GCC, Clang, MSVC) ignore your inline keyword when it doesn’t make sense, and will inline methods without the keyword if they think it’s beneficial (especially at higher optimization levels like -O2 or -O3). Your inline is just a hint, not a command.
Quick summary
There’s no universal number, but as a rule:
- Inline 1-3 line trivial methods (getters/setters, simple ops)
- Consider 5-10 line methods only if they’re hot and simple
- Leave anything longer to the compiler’s optimization logic
内容的提问来源于stack exchange,提问作者rety

