SparseArrays.jl
SparseArrays.jl copied to clipboard
spzeros(T, n) allocates
According to documentation:
spzeros([type,]m[,n])
.... No storage will be allocated for nonzero values during construction
However, it does allocate:
function spallo(n)
for i in 1:n
spzeros(Int, 10)
end
end
@allocated spallo(10)
1280
julia> @allocated spallo(100)
12800
It doesn't allocate for nonzero values. It still has to allocate for the SparseMatrixCSC data structure, roughly 1 int per column.
spzerosdoes not create aSparseMatrixCSC, but aSparseVector. I guess thatspzerosallocates because it contains 2 vectors (one for dims and one for values). Even if they're initialized as empty, Julia allocates for empty vectors. See code below- In any case, I think the reason why it allocates is not important. What is important is that the documentation says that it does not allocate, and it does. This means that it's misleading when optimized code is required, since the documentation seems to imply that using it and pushing data might have the same performance as setting the data directly through other SparseVector constructors.
function f(n)
for i in 1:n
a= Int[]
resize!(a,1)
end
end
f (generic function with 1 method)
julia> @allocations f(10)
20
That is right, the empty vectors will be allocated. You are right - the documentation could be improved to not give the wrong impression. If you could make a PR that would be great.