多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
inline 关键字允许函数体被直接插入到它们调用位置。这是一个强大的优化工具,但是应该审慎使用,并不是所有函数都适用inline行为。下面的例子演示了基本的用法: > The inline keyword allows function bodies to be directly inserted in place of calls to them. This can be a powerful optimization tool,but should be used judiciously as not all functions are good candidates for inline behavior. The following example demonstrates the basic usage: ~~~ class Main { static inline function mid(s1:Int, s2:Int) { return (s1 + s2) / 2; } static public function main() { var a = 1; var b = 2; var c = mid(a, b); } } ~~~ 生成的JavaScript输出揭示了内联的效果: > The generated JavaScript output reveals the effect of inline: ~~~ (function () { "use strict"; var Main = function() { } Main.main = function() { var a = 1; var b = 2; var c = (a + b) / 2; } Main.main(); })(); ~~~ 显然,字段mid被生成的函数体(s1 + s2)/2替换掉了调用 mid(a,b),s1被替换为 a ,s2被替换为b。这可以避免一个函数调用,根据目标和出现的频率,可以产生显著的性能改进。 > As evident, the function body (s1 + s2) / 2 of field mid was generated in place of the call to mid(a, b), with s1 being replaced by a and s2 being replaced by b. This avoids a function call which,depending on the target and frequency of occurrences,may yield noticeable performance improvements. 并不总是容易判断是否一个函数要限定为内联函数。没有编写表达式的短函数(如a=形式的赋值)通常是一个好的选择,但是有时候更复杂的函数也可以使用内联。然而,在一些情况下内联可以实际上损害部分性能,例如,因为编译器必须创建临时变量服务于复杂的表达式。 > It is not always easy to judge if a function qualifies for being inline. Short functions that have no writing expressions (such as a = assignment) are usually a good choice, but even more complex functions can be candidates. However, in some cases inlining can actually be detrimental to performance, e.g. because the compiler has to create temporary variables for complex expressions. 内联并不保证执行。编译器可能由于多种原因取消内联,用户也可以通过 --no-inline 命令行参数来禁止内联。唯一的例外是如果类是 extern(第6.2节)或者如果泪字段有 :extern 元数据(第6.9节),这种情况内联被禁止。如果她不能被执行,编译器发出一个错误。 > Inline is not guaranteed to be done. The compiler might cancel inlining for various reasons or a user could supply the --no-inline command line argument to disable inlining. The only exception is if the class is extern (6.2) or if the class field has the :extern metadata (6.9), in which case inline is forced. If it cannot be done, the compiler emits an error. 重要的是依赖内联时要记得这个: > It is important to remember this when relying on inline: ~~~ class Main { public static function main () { } static function test() { if (Math.random() > 0.5) { return "ok"; } else { error("random failed"); } } @:extern static inline function error(s:String) { throw s; } } ~~~ 如果正确的调用error是内联的,程序编译正确,因为控制流检查器满意内联的throw(第5.22节)表达式。如果内联部执行,编译器只发现一个error函数的调用并发出错误 A return is missing here。 > If the call to error is inlined the program compiles correctly because the control flow checker is satisfied due to the inlined throw (5.22) expression. If inline is not done,the compiler only sees a function call to error and emits the error A return is missing here.