Is there a way to avoid allocations with view and missing values? If I change the inner loop to sum then there are allocations in both tests.
using BenchmarkTools
X = randn(10, 1000)
Xm = convert(Array{Union{Float64, Missing}}, X)
function colsums(x::Array{T}) where T
y = Vector{T}(undef, size(x, 2))
@inbounds for i in 1:size(x, 2)
xx = view(x, :, i)
x0 = 0
for j in eachindex(xx)
x0 += xx[j]
end
y[i] = x0
end
return y
end
@btime colsums(X);
@btime colsums(Xm);
Your x0 is being initialized as an Int and winds up getting promoted on every iteration. This is definitely causing a lot of extra allocations, though Iām not quite sure why it goes so much more badly wrong with missng.
function colsums(x::Array)
y = Vector{eltype(x)}(undef, size(x, 2))
@inbounds for i ā 1:size(x, 2)
xx = view(x, :, i)
x0 = zero(eltype(x))
for j ā eachindex(xx)
x0 += xx[j]
end
y[i] = x0
end
y
end
O, thanks for spotting this, this mistake was from the MWE only, it didnāt solve my problem. What solved big part of the problem was removing an unneeded where T from some functions.
sum is probably slower because it does pairwise aggregation for better accuracy and therefore has some overhead.
sum(xx) is slower than a loop because it isnāt inline, so the compiler heap allocates your views, and because 10 rows is too short for vectorization.
What solved big part of the problem was removing an unneeded where T from some functions.
I keep getting bit by that, and would love to hear if anyone has a good solution.
Once upon a time this triggered an error. I wish that weāre still the case.
A while a go I opened an issue for LanguageServer.jl to issue a warning.
The code I am encountering this problem has some really strange other issues, too (e.g. it reaches the unreachable in julia 1.0, 1.1, 1.2, and master due to some typeinference bug and the only thing that helps is manually inlining everything) and I am really struggling to create a reproducible example.
Cool, following the issue. I should try getting LanguageServer.jl working in my emacs again.
I didnāt try SpaceMacs because I wasnāt familiar with the vim keybindings either (although Iāve been using ergoemacs, which has only slightly different movement keys ā maybe I should have gone evil/spacemacs instead), and have things configured in a way I like otherwise.
That mostly means treemacs (which is also integrated into spacemacs), so Iāll probably give it a try sometime.
Having to manually inline everything is worse than having to @inline problem functions, like I do to work around this isssue.
How far does the āeverythingā go in āmanually inlining everythingā? Iād hope you donāt have to inline getindex calls, for example.
Luckily not getindex, I have to manually inline all the imported functions from a package which I am extending (which is ~3 layers deep) . The weird/interesting/annoying part is, that it works fine in one case, but not in a very similar one.