Skip to content

Small utility for Haxe that wraps function types as delegate objects

License

Notifications You must be signed in to change notification settings

paulsgcross/haxe-delegates

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

53 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

haxe-delegates

Small utility for Haxe that wraps function types as Delegate objects. Enforces type-strictness and can be faster on some platforms (~40% faster for non-inlined functions and ~200% faster for inlined on the hxcpp target). Very useful within performance-critical code where delegates/functions need to be called. Delegate building is much more expensive.

How to use it:

Import haxe.delegates.* and simply use the delegate type with a function type as your parameter, like so:

var delegate : Delegate<(Int, Int)->Int> = DelegateBuilder.from(myFunction);

public function myFunction(a : Int, b : Int) : Int {
    return a + b;
}

or,

var delegate : Delegate<(Int, Int)->Int> = DelegateBuilder.from((a : Int, b : Int) -> (a+b : Int)));

For inlined functions, it is important to use the cast notation (x : Type). This is not for casting the value, instead it is used by the builder to resolve the return type without the need to determine it implicitly.

What's actually going on?

These macros generate concrete types at compile time. As such, they're not designed to replace Haxe function types (which are light-weight and useful when used during start-up). The trade-off when using delegates for speed is a slightly bigger source-code.

Why?

Some Haxe targets are required to unbox value types from function types when called (which then need to be garbage collected). By encapsulating function calls, we can avoid this unboxing and even enforce type-strictness on function type parameters. The following example will fail:

var delegate : Delegate<Dynamic->Void> = DelegateBuilder.from(myFunction);

// Must have Dynamic as first argument...
public function myFunction(a : Int) : Void {
    trace(a);
}

Future work:

It may be possible to wrap delegates that get generated by their respective builders into singletons, or caching, to reduce any performace impacts during run-time if one wishes to create delegates frequently.

About

Small utility for Haxe that wraps function types as delegate objects

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages