# Performance enhancement for setindex! for sparse array

**URL:** <https://discourse.julialang.org/t/performance-enhancement-for-setindex-for-sparse-array/8451>\
**Category:** General Usage\
**Tags:** question\
**Created:** [January 18, 2018, 5:30am UTC](https://discourse.julialang.org/t/performance-enhancement-for-setindex-for-sparse-array/8451 "2018-01-18T05:30:06Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Chong\_Wang](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chong_wang/32/20307_2.png) [@Chong\_Wang](https://discourse.julialang.org/u/Chong_Wang)\
**Post date:** [January 18, 2018, 5:30am UTC](https://discourse.julialang.org/t/performance-enhancement-for-setindex-for-sparse-array/8451/1 "2018-01-18T05:30:06Z")

</div>

I have a function that spends most of its time in setindex! for sparse array. Part of the profiling results is

```julia
    5339 ...rse/sparsematrix.jl:2316; setindex!(::SparseMatrixCSC{C...
     5338 ./array.jl:852; insert!
    10201 ...rse/sparsematrix.jl:2317; setindex!(::SparseMatrixCSC{C...
     10200 ./array.jl:852; insert!(::Array{Complex{Float...

```

Any idea how to optimize this function? Is there anything like pre-allocation?

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [January 18, 2018, 5:39am UTC](https://discourse.julialang.org/t/performance-enhancement-for-setindex-for-sparse-array/8451/2 "2018-01-18T05:39:04Z")

</div>

Use `sparse(I, J, V,[m, n, combine])` if you’re going to be building up a sparse array. Building them up by using `setindex!` is just a bad idea given how they are stored, while building up the pairings `(i,j,value)` is quick. Note that sparse matrices are not stored as `(i,j,value)` since they are “compressed” (that’s what CSC means), and after they are compressed it’s not as easy to change the sparsity pattern. This storage is optimized for column slicing and matrix multiplication, but not for changing values (or slicing rows).
