haxe icon indicating copy to clipboard operation
haxe copied to clipboard

Selective @:generic

Open Simn opened this issue 5 months ago • 2 comments

I've been fighting with performance problems for classes that wrap native arrays/Vector like this:

import haxe.ds.Vector;

class Page<T> {
	public final data:Vector<T>;

	public function new(size:Int) {
		data = new Vector(size);
	}

	public function get(index:Int) {
		return data[index];
	}

	public function set(index:Int, value:T) {
		data[index] = value;
	}
}

function main() {
	var page = new Page<Int>(8);
	page.set(1, 1);
	page.set(2, 2);
	page.set(3, 3);
	trace(page.get(1));
}

This necessarily has to wrap all integers in order to store them, because Vector<T> becomes [java.lang.Object on the JVM target and something similar on other static targets. We can get much nicer code output by using @:generic class Page<T>, in which case the physical storage will end up as a real [I array and no wrapping is necessary.

What's annoying about @:generic though is that it generates specialization classes for everything, and in many cases that makes no sense as far as performance is concerned. So my idea would be to allow it being selective, e.g. @:generic(Page<Int>, Page<Float>, Page<Bool>) class Page<T>. This would then specialize the class only for these concrete types, while using the default implementation for everything else.

I'm interested in @ncannasse's opinion on this!

Simn avatar Jun 15 '25 06:06 Simn