似乎只是调用了该函数。 什么时候需要? 似乎比直接调用该函数要慢得多。
答案 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
打电话给foo
时
bar
本质上已经被编译,
因此foo
已优化为静态调用。
(即使在这种情况下也可能内联)。
因此bar
无法看到通过foo
创建的新覆盖的@eval
速度较慢,因为它阻止了将调用编译为静态调度。
通常,您永远不需要
这样的代码不好。
尝试避免在函数内部使用@eval
。
很难推理。