# Avoid unnecessary computations with (sparse) Arrays

**URL:** <https://discourse.julialang.org/t/avoid-unnecessary-computations-with-sparse-arrays/32473>\
**Category:** General Usage\
**Tags:** array\
**Created:** [December 19, 2019, 8:55am UTC](https://discourse.julialang.org/t/avoid-unnecessary-computations-with-sparse-arrays/32473 "2019-12-19T08:55:42Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rveltz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rveltz/32/2707_2.png) [@rveltz](https://discourse.julialang.org/u/rveltz)\
**Post date:** [December 19, 2019, 8:55am UTC](https://discourse.julialang.org/t/avoid-unnecessary-computations-with-sparse-arrays/32473/1 "2019-12-19T08:55:42Z")

</div>

Hi,

I would like to avoid unnecessary computations in computing shifts of matrices like for example `0*I + 1*J`. I thought about the code below, but this is not really a viable strategy because I would like to dispatch on the value `y = 1`. Is there a better way to do this?

Thank you for your suggestions,

Best.

```julia
using LinearAlgebra, SparseArrays
const Jtmp = sprand(10^4,10^4,0.001)
f(x,y) = x * I + y .* Jtmp
f(x::Nothing, y) = y .* Jtmp
f(x::Nothing, y::Nothing) = Jtmp

```

---

<div class="post-metadata">

**Author:** ![mohamed82008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mohamed82008/32/18171_2.png) [@mohamed82008](https://discourse.julialang.org/u/mohamed82008)\
**Post date:** [December 19, 2019, 12:39pm UTC](https://discourse.julialang.org/t/avoid-unnecessary-computations-with-sparse-arrays/32473/2 "2019-12-19T12:39:21Z")

</div>

Why do you need dispatch? Your matrix is large I assume, so nothing wrong with a good old if statement, hardly costs you anything. And if `y` is a constant in your code, constant propagation may even kick in.

---

<div class="post-metadata">

**Author:** ![rveltz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rveltz/32/2707_2.png) [@rveltz](https://discourse.julialang.org/u/rveltz)\
**Post date:** [December 19, 2019, 1:17pm UTC](https://discourse.julialang.org/t/avoid-unnecessary-computations-with-sparse-arrays/32473/3 "2019-12-19T13:17:21Z")

</div>

I agree, thank you for your suggestion.
