考虑下面的例子,其中一个功能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
Run Code Online (Sandbox Code Playgroud)
因为到那时,bar
调用foo
bar
已经被编译,因此foo
已经优化为静态调用。(即使在这种情况下也可能内联)。
因此bar
看不到foo
通过创建的新覆盖@eval
它比较慢,因为它阻止了调用编译为静态调度。
通常,您永远都不需要此代码。尝试避免使用@eval
内部函数。很难推理。