The inline keyword can be used in two ways: for static variables and for any kind of method.

Inlining Static Variables

For static variables, it's pretty simple. Every time the variable is used, its value will be used instead of the variable access. Example :

class Test {
    static inline var WIDTH = 500;
    static function main() {

Using "inline" adds a few restrictions :

  • the variable must be initialized when declared
  • the variable value cannot be modified

The main advantage of using "inline" is that you can use as many variables as you want without slowing down your code with these variables accesses since the value is directly replaced in the compiled/generated code.

Inlining Methods

The principle is the same for a method. The less expensive function call is the one that is never done. In order to achieve that for small methods that are often called, you can "inline" the method body a the place the method is called.

Let's have a look at one example :

class Point {
   public var x : Float;
   public var y : Float;
   public function new(x,y) { this.x = x; this.y = y; }
   public inline function add(x2,y2) { return new Point(x+x2,y+y2); }
class Main {
   static function main() {
       var p = new Point(1,2);
       var p2 = p.add(2,3);
       // is the same as writing :
       var p2 = new Point(p.x+2,p.y+3);

Again, there's some limitations to inline functions :

  • they cannot be redefined at runtime
  • they cannot be overridden in subclasses
  • an function containing "super" accesses or declare another function cannot be inlined
  • if the inline function has arguments, then the arguments evaluation order is undefined and some arguments might even be not evaluated, which is good unless they have some expected side-effects
  • if the inline returns a value, then only "final returns" are accepted, for example :

inline function foo(flag) { return flag?0:1; } // accepted
inline function bar(flag) { if( flag ) return 0; else return 1; } // accepted
inline function baz(flag) { if( flag ) return 0; return 1; } // refused

Apart from these few restrictions, using inline increases the compiled/generated codesize but brings a lot of additional speed for small methods. Please note that it's also possible to inline static methods.

«« Conditional Compilation

version #5750, modified 2009-04-13 19:03:17 by ncannasse