Saturday, March 27, 2010

HaXe Vs Flex: Constant If Removal

When the condition of an if is constant the compiler can decide to remove the condition and body from the generated bytecode. This reduces space and (possibly) improves execution performance.

I set out to test the haXe and flex compilers, to see if any of them would apply such optimizations. To do so I used hxswfml, a tool which lets you convert swf files to xml or hx files that represent the bytecode in a very readable manner.

Flex SDK 4:

package 
{
import org.flashdevelop.utils.FlashConnect;
import flash.display.Sprite;
import flash.events.Event;

public class Main extends Sprite
{
private static const a : uint = 1;
public function Main():void
{
if ( a == 0 ) {
FlashConnect.trace( "Test A" );
}

const b : uint = 1;
if ( b == 0 ) {
FlashConnect.trace( "Test B" );
}

var c : uint = 1;
if ( c == 0 ) {
FlashConnect.trace( "Test C" );
}

if ( false ) {
FlashConnect.trace( "Test D" );
}
}
}
}

The result was that only Test D was optimized away from the bytecode.

HaXe 2.05 Compiler:

package ;

import flash.Lib;
import org.flashdevelop.utils.FlashConnect;

class Main
{
static inline var b = 1;
static inline var c = 0;

static function main()
{
var a = 1;
if ( a == 0 ) {
FlashConnect.trace("Test A");
}

if ( b == 0 ) {
FlashConnect.trace("Test B");
}

if ( b == c ) {
FlashConnect.trace("Test C");
}

if ( false ) {
FlashConnect.trace("Test D");
}

}
}

Tests B to D were removed, Test A remained.


Both as3 and haxe provide means for conditional compilation, however they both require you to define the preprocessor variables outside of the sourcecode. HaXe's inline variables allow configuration of the source compilation in a less powerful but less tedious way.

I was disappointed that haXe didn't optimize away all cases though.


No comments:

Post a Comment