多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
通常,Haxe编译器只生成一个单独的类或者函数,即使它有类型参数。生成的代码之后可能必须执行一些类型检查可能会影响一些性能。这发生在一个自然抽象概念中,目标语言的代码生成器必须假设一个类型参数可以是任何类型。 > Usually, the Haxe Compiler generates only a single class or function even if it has type parameters. This results in a natural abstraction where the code generator for the target language has to assume that a type parameter could be of any type. The generated code then might have to perform some type checks which can be detrimental to performance. 一个类或者函数可以通过使用 :generic 元数据(第6.9节)归类为泛型。这导致编译器每个类型参数和破损的名字的混合,发射一个不同的类/函数。一个这样的规范可以产生一个性能关键代码的减少分配到静态目标语言(第2.2节)的生成文件大小: > A class or function can be made generic by attributing it with the :generic metadata (6.9). This causes the compiler to emit a distinct class/function per type parameter combination with mangled names. A specification like this can yield a boost in performance-critical code portions on static targets (2.2) at the cost of a larger output size: ~~~ @:generic class MyValue<T> { public var value:T; public function new(value:T) { this.value = value; } } class Main { static public function main() { var a = new MyValue<String>("Hello"); var b = new MyValue<Int>(42); } } ~~~ 似乎不常见这里的显式类型 MyValue<String>,因为我们通常让类型推断(第3.6节)处理它。尽管如此,它确实需要在这种情况下被需要。编译器必须了解泛型类的准确类型一经构建。JavaScript输出显示结果: > It seems unusual to see the explicit type MyValue<String> here as we usually let type inference (3.6) deal with this. Nonetheless, it is indeed required in this case. The compiler has to know the exact type of a generic class upon construction. The JavaScript output shows the result: ~~~ (function () { "use strict"; var Test = function() { }; Test.main = function() { var a = new MyValue_String("Hello"); var b = new MyValue_Int(5); }; var MyValue_Int = function(value) { this.value = value; }; var MyValue_String = function(value) { this.value = value; }; Test.main(); })(); ~~~ 我们可以确定 MyValue<String>和MyVlue<Int> 已经变成 MyValue_String 和MyValue_Int 。这类似于泛型函数: > We can identify that MyValue<String> and MyValue<Int> have become MyValue_String and MyValue_Int respectively. This is similar for generic functions: ~~~ class Main { static public function main() { method("foo"); method(1); } @:generic static function method<T>(t:T) { } } ~~~ 再一次,JavaScript输出使其非常明显: > Again, the JavaScript output makes it obvious: ~~~ (function () { "use strict"; var Main = function() { } Main.method_Int = function(t) { } Main.method_String = function(t) { } Main.main = function() { Main.method_String("foo"); Main.method_Int(1); } Main.main(); })(); ~~~