You’re right, I tried to create a minimal example to illustrate a problem I’m seeing in actual code, where I’m not using any globals. The following example has no globals, and is closer to my actual code, while still exhibiting the same problem.
function fun2(; A::AbstractVector{Float64} = [1.0])
B = copy(A)
B .*= (A-1.0) ./ (1.0-A)
end
function fun1()
fun2(A = [1.0])
end
fun1()
It uses 1 second in Julia 0.6.4 and 46 ms in Julia 0.7.0. Using @code_warntype, it seems that the problem stems from the use of an abstract keyword argument type? I don’t recall hearing about this before, is this an issue that has been fixed in Julia 0.7.0?
@code_warntype fun2(A = [1.0])
Julia 0.6.4:
A::AbstractArray{Float64,1}
B::Any
Body:
begin
...
end::Any
Hmm, ok, that could explain part of it, but there’s also the keyword argument type instability, right? This is my understanding of what’s going on in my two examples, please correct me if something doesn’t sound right:
Example 1:A, B, C and y are not defined, so when fun2 is JIT compiled, their types are not known, and inference takes a long time in Julia 0.6.4, due to broadcasting + inference not working well together. In Julia 0.7, broadcasting + inference is a lot faster.
Example 2: The type of B is not known by the compiler in Julia 0.6.4, so again inference takes a long time. In Julia 0.7, the compiler is able to figure out the type of B, so this is fast (and would be fast regardless since broadcasting + inference works better).
Conclusions:
Upgrade to 0.7 as soon as possible
While still on 0.6.4, avoid keyword arguments with abstract types, since it leads to type instability
@ChrisRackauckas, do you think it’s a good idea to remove gotcha #7 given that it isn’t needed for versions 1.0 and above. If you don’t want to remove it, could you consider adding a comment in the main text itself?
I became aware of not needing to do the steps in #7 through the comments on your blog post but it’s probably useful to make a small comment on the main text too.
Yeah, I guess that would be nice too. I’m particularly fond of this blog post and regularly suggest it to newcomers on the forum. I personally learnt a lot from it when I started ~10 months ago. An update on some other things to make the post more relevant for newer versions would be an amazing public good!