# Avoiding allocations when normalizing a vector

**URL:** https://discourse.julialang.org/t/avoiding-allocations-when-normalizing-a-vector/113913
**Category:** Performance
**Tags:** question, staticarrays
**Created:** [May 6, 2024, 2:49pm UTC](https://discourse.julialang.org/t/avoiding-allocations-when-normalizing-a-vector/113913 "2024-05-06T14:49:51Z")
**Posts on this page:** 1
**Showing post:** 7

<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: [May 6, 2024, 5:32pm UTC](https://discourse.julialang.org/t/avoiding-allocations-when-normalizing-a-vector/113913/7 "2024-05-06T17:32:19Z")

</div>

> [@Domenico\_Lahaye](#):
>
> ```julia
> @btime hcubature($(rp->integrand(r, Point3D(rp[1],rp[2],0))), $(0,0), $(1,1))[1]
> 
> ```

That’s not enough, because your variable `r` is still a [non-constant global variable](https://docs.julialang.org/en/v1/manual/performance-tips/#Avoid-untyped-global-variables).

If you put this all [into a function](https://docs.julialang.org/en/v1/manual/performance-tips/#Performance-critical-code-should-be-inside-a-function) it should be better:

```julia
using LinearAlgebra, StaticArrays, HCubature, BenchmarkTools

const Point3D = SVector{3,Float64}
integrand(r, rp) = normalize(r - rp)
foo(r) = hcubature(rp->integrand(r, Point3D(rp[1],rp[2],0)), (0,0), (1,1))[1]

```

gives

```julia
julia> @btime foo($(Point3D(0,0,0)));
  67.375 μs (5 allocations: 65.92 KiB)

```

for me.

(Using your definition of `Point3D` from [your other thread](https://discourse.julialang.org/t/svector-and-type-stabilty/113391/3), without which your code is not runnable. Please try to make _self contained_ runnable examples in your posts.)

---

_[View the full topic](https://discourse.julialang.org/t/avoiding-allocations-when-normalizing-a-vector/113913)._
