# Loop vs vectorization

**URL:** https://discourse.julialang.org/t/loop-vs-vectorization/104796
**Category:** Performance
**Created:** [October 10, 2023, 11:21am UTC](https://discourse.julialang.org/t/loop-vs-vectorization/104796 "2023-10-10T11:21:02Z")
**Posts on this page:** 1
**Showing post:** 5

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [October 10, 2023, 12:40pm UTC](https://discourse.julialang.org/t/loop-vs-vectorization/104796/5 "2023-10-10T12:40:15Z")

</div>

> [@Alberto\_Roman](#):
>
> I have a partial differential equation to solve using finite difference. I am trying to understand if it is better to use a vectorized version or a loop version to calculate the right hand side of the equation, which has the spatial discretization.

For finite differences, I would tend to prefer loops (properly written, as noted by @lmiq and others above). Loops just give you more flexibility for this kind of thing (as well as excellent performance).

For example, see this post for example code of writing a scalar-wave equation finite-difference routine using loops that, combined with Julia’s [`CartesianIndex` facilities](https://julialang.org/blog/2016/02/iteration/), support _arbitrary dimensionality_ with a _single_ loop: [Seemingly unnecessary allocation within for loop - #8 by stevengj](https://discourse.julialang.org/t/seemingly-unnecessary-allocation-within-for-loop/72556/8)

---

_[View the full topic](https://discourse.julialang.org/t/loop-vs-vectorization/104796)._
