SparseArrays.jl icon indicating copy to clipboard operation
SparseArrays.jl copied to clipboard

spzeros(T, n) allocates

Open dpinol opened this issue 2 years ago • 3 comments

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

dpinol avatar May 09 '23 15:05 dpinol

It doesn't allocate for nonzero values. It still has to allocate for the SparseMatrixCSC data structure, roughly 1 int per column.

ViralBShah avatar May 09 '23 17:05 ViralBShah

  • spzeros does not create a SparseMatrixCSC, but a SparseVector. I guess that spzeros allocates 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

dpinol avatar May 09 '23 17:05 dpinol

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.

ViralBShah avatar May 09 '23 19:05 ViralBShah