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

Julia 为什么朱莉娅有“Base.invokelatest”?,julia,Julia,它似乎只是调用了函数。 什么时候需要? 它似乎比直接调用函数慢得多。考虑以下示例, 其中,函数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 b

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

考虑以下示例, 其中,函数
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
调用
foo
bar
就其性质而言已被编译, 因此,
foo
作为一个静态调用进行了优化。 (即使在这种情况下也可能是内联的)

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

它的速度较慢,因为它阻止调用向下编译为静态分派

一般来说,你不应该需要这个 这种代码不好。 尽量避免在函数内部使用
@eval

这很难解释。

在任何不使用
eval
的情况下都会发生这种情况吗?可能还有一些类似于
eval
的操作。我使用
包括
@无处不在