简体   繁体   English

在ironpython中导入模块时会发生什么?

[英]What happens when import a module in ironpython?

In CPython, I think, import means compile the py file to a pyc file and execute the file in the current frame, and the next time CPython will load the pyc file directly without compiling again. 在CPython中,我认为,import意味着将py文件编译为pyc文件并在当前帧中执行该文件,下次CPython将直接加载pyc文件而不再编译。 What about import in ironpython? 如何进口铁腕? I guess ironpython don't have a pyc-like format. 我猜ironpython没有类似pyc的格式。 Does it compile every time when import? 每次导入时都会编译吗?

Yes, IronPython recompiles the imported module on every run. 是的,IronPython会在每次运行时重新编译导入的模块。 Twice, actually. 实际上是两次。

It's complicated. 情况很复杂。

On the first pass, the Python code is parsed into an AST, the AST is converted into a DLR expression tree, and the expression tree is stored. 在第一遍中,Python代码被解析为AST,AST被转换为DLR表达式树,并且存储表达式树。 When it is time to execute it, the expression tree is compiled into a set of instructions for a simple stack-based interpreter and the module code is executed on that interpreter. 当需要执行它时,表达式树被编译成一组简单的基于堆栈的解释器的指令,模块代码在该解释器上执行。 It's not fast when running, but it has very little start up time. 跑步时速度不快,但启动时间很短。

After a piece of code has run for a while, IronPython gets fed up with how slow it is, goes back to the expression tree, and recompiles the code into a .NET delegate. 在一段代码运行一段时间后,IronPython厌倦了它的速度,回到表达式树,并将代码重新编译成.NET委托。 This means that it gets converted to MSIL and then native code by the .NET JIT. 这意味着它将被.NET JIT转换为MSIL,然后转换为本机代码。 This code is fast to execute, but takes time to create. 此代码执行起来很快,但需要时间来创建。

This conversion is done a per-function (or even per-loop) basis, so that if you use one function from a module repeatedly and none of the rest, only the one commonly-used function will undergo full IL code generation and JITting. 这种转换是基于每个函数(甚至每个循环)完成的,因此如果您重复使用模块中的一个函数而不使用其余函数,则只有一个常用函数将经历完整的IL代码生成和JITting。

None of this compilation is saved to disk, however. 但是,这些编译都没有保存到磁盘。 The pyc.py program included with IronPython can precompile the code, but it's not done automatically because the code generated at runtime is different than the code generated by pyc.py. IronPython附带的pyc.py程序可以预编译代码,但它不是自动完成的,因为在运行时生成的代码与pyc.py生成的代码不同。 The runtime code is usually collectible, while the code generated by pyc.py is not - and generating non-collectible code at runtime leads to memory leaks. 运行时代码通常是可收集的,而pyc.py生成的代码不是 - 并且在运行时生成不可收集的代码会导致内存泄漏。 pyc.py should make imports faster by saving a few steps, but I'm not sure by how much. pyc.py应该通过节省几个步骤来加快导入,但我不确定多少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM