类型稳定性如何使Julia变得如此快? [英] How does type stability make Julia so fast?

查看:71
本文介绍了类型稳定性如何使Julia变得如此快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说类型稳定性是让Julia变得如此快速的原因,同时仍然像其他解释性语言(如Python)一样具有表现力.

I've heard that type stability is what makes Julia so fast, while still being as expressive as other interpreted languages such as Python.

推荐答案

类型稳定性允许编译器在编译时直接从输入类型确定函数的输出类型.因为Julia对每种输入类型都专门进行编译,所以这意味着,如果所有函数都是类型稳定的,则编译器可以推断出函数调用内每个值的类型.发生这种情况时,Julia的JIT编译器实质上将创建该方法的静态类型版本,并构建LLVM IR来编译该静态版本,其中该静态版本与使用clang(LLVM)编译的C本质上是相同的汇编代码.

Type stability allows the compiler to determine the output types of a function directly from the input types at compile time. Because Julia specializes the compilation on every input type, this means that if all functions are type stable, the compiler can deduce the types of every value inside of a function call. When this occurs, Julia's JIT compiler will essentially create a statically typed version of the method and build the LLVM IR to compile that static version, where that static version is essentially the same assembly code as C compiled with clang (LLVM).

这意味着,如果编译器可以推断出每个变量的基本类型,它将并且将发出强制保留这些类型的代码,就像完全注释了C代码一样. Julia的动态方式是,当它不成立时,它将装箱"变量,本质上创建一个新类型,显示我不知道类型是什么",并添加用于强制类型检查的代码并在运行时调度计算以处理动态性.因此,如果知道所有类型信息,Julia的动态性就会消失,甚至在运行的代码中甚至不再存在.

What this means is that, if the compiler can deduce the basic types on every variable, it will and it will emit code that forces those types to hold, just as though it was fully annotated C code. The way that Julia is dynamic is that when this doesn't hold, then it will "box" the variables, essentially creating a new type that says "I don't know what the type is" and add in code for forcing type checks and dispatch computations at runtime to handle the dynamicness. So if all type information is known, the dynamicness of Julia compiles away and ceases to even exist in the code that is ran.

这也是为什么多重分派对语言如此重要的原因,因为多重分派意味着f(x)f(x::Float64)具有不同的方法(即使您未指定具体版本,编译器也会推导和使用这种方式(称为自动类型专用化),现在具体版本比一般版本更稳定.将多个分派作为功能公开实际上只是允许您拦截编译的这一阶段并允许更改type-> code关系.

This is also why multiple dispatch is so crucial to the language, since multiple dispatch then means that f(x) has a different method for f(x::Float64) (even if you don't specify the concrete version, the compiler will deduce and use that, called automatic type-specialization), and now that concrete version is more likely to be stable than the general version. Exposing multiple dispatch as a feature is really just allowing you to intercept this stage of the compilation and allow changing the type->code relationship.

这篇关于类型稳定性如何使Julia变得如此快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆