朱莉娅为什么会有“ Base.invokelatest”?

时间:2019-09-01 20:46:07

标签: julia

似乎只是调用了该函数。 什么时候需要? 似乎比直接调用该函数要慢得多。

1 个答案:

答案 0 :(得分:9)

考虑以下示例, 函数bar在调用之前使用@eval重新定义foo

julia> foo() = 1
foo (generic function with 2 methods)

julia> function bar()
           @eval foo() = 2  # remember @eval runs at global scope
           foo()
       end
bar (generic function with 1 method)

julia> bar()
1   # Got old version

julia> function bar2()
           @eval foo() = 3  # remember @eval runs at global scope
           Base.invokelatest(foo,)
       end
bar2 (generic function with 1 method)

julia> bar2()
3

由于bar打电话给foobar本质上已经被编译, 因此foo已优化为静态调用。 (即使在这种情况下也可能内联)。

因此bar无法看到通过foo创建的新覆盖的@eval

速度较慢,因为它阻止了将调用编译为静态调度。

通常,您永远不需要 这样的代码不好。 尝试避免在函数内部使用@eval。 很难推理。