Avoiding allocations when normalizing a vector

That’s not enough, because your variable r is still a non-constant global variable.

If you put this all into a function it should be better:

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> @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, without which your code is not runnable. Please try to make self contained runnable examples in your posts.)

1 Like