[go: up one dir, main page]

haxe-delegates

Small utility for Haxe that wraps function types as delegate objects. Enforces type-strictness and is faster on some targets.
https://github.com/thispolo/haxe-delegates

To install, run:

haxelib install haxe-delegates 1.0.0 

See using Haxelib in Haxelib documentation for more information.

README.md

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.

Contributors
PaulSGCross
Version
1.0.0
Published
3 years ago
License
MIT

All libraries are free

Every month, more than a thousand developers use Haxelib to find, share, and reuse code — and assemble it in powerful new ways. Enjoy Haxe; It is great!

Explore Haxe

Haxe Manual

Haxe Code Cookbook

Haxe API documentation

You can try Haxe in the browser! try.haxe.org

Join us on GitHub!

Haxe is being developed on GitHub. Feel free to contribute or report issues to our projects.

Haxe on GitHub